且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在一行中选择多行?

更新时间:2023-02-05 11:22:02

你不能在任何SQL实现中以这种方式组合行。

但是如果你只有一个字段值你想要以这种方式组合,你可以使用一些串联聚合。但是,由于您没有告诉我们您使用哪种RDBMS,因此无法确定您是否拥有此类功能。我们假设你有SQL Server。在这种情况下,您可以使用以下方法: https:// www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/ [ ^ ], SQL Server世界中的字符串聚合 [ ^ ],http://groupconcat.codeplex.com/。 [ ^ ]。



仍然,因为你还没有指定分组逻辑(你有6个)在您的输入中的row3...),聚合是没有用的。但是我们假设您想按某种顺序将它们按N分组。



假设解决了最新的链接,并且下表:

You can't combine rows this way in any of SQL implementations.
But if you have only a single field value you want to combine this way, you can use some concatenation aggregate. But as you haven't told us which RDBMS you use, it is impossible to say if you have such a feature at hand or not. Let's suppose you have SQL Server. In this case you these approaches: https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/[^], String Aggregation in the World of SQL Server[^], http://groupconcat.codeplex.com/.[^].

Still, as you haven't specified the grouping logic (you have 6 "row3" in your imput...), the aggregate is of no use. But let's assume you want to group them by N in some order.

Assuming the solution of the latest link, and following table:
CREATE TABLE [dbo].[test](
    [number] [int],
    [id] [int] IDENTITY(1,1) NOT NULL
)



您可以发出以下查询:


You can issue following query:

WITH MYCTE (group_id, number)as
(
    select
    ROW_NUMBER() OVER(ORDER BY ID) / 3 as group_id, number
    FROM test
)
select dbo.GROUP_CONCAT_D(number, ', ') from MYCTE group by group_id


基于Reb Cabin对问题的回答: linq get sets with adjacent [ ^ ],我建议使用Linq实现:



Based on Reb Cabin's answer to the question: linq get sets with adjacent[^], i'd suggest to use Linq to achieve that:

var nums = new [] {1, 2, 3, 6, 7, 8, 14, 15};

var @group = 0;
nums.Zip(nums.Skip(1).Concat(new [] {nums.Last()}),
    (n1, n2) => Tuple.Create(n1, (n2 - n1) == 1 ? @group : @group++))
    .GroupBy (t => t.Item2)
    .Select (g => new {Group = string.Join(",", g.Select(x => x.Item1)), Count = g.Count()})
    .Dump();





结果:



Result:

Group Count
1,2,3 3
6,7,8 3
14,15 2