如何在一行中选择多行? [英] How to select multi row in one row?

查看:101
本文介绍了如何在一行中选择多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我在多行选择时执行此操作,当排的行没有继续时:



标记

第1行: 1

第2行:2

第3行:3

第4行:6

第5行:7

第6行:8

第7行:14

第8行:15



答案将是:

第1行:1,2,3

第2行:6,7,8

第3行:14,15

Hi please help me to do this on multi row select when sort of row is'nt continued:

marks
Row1: 1
Row2: 2
Row3: 3
Row4: 6
Row5: 7
Row6: 8
Row7: 14
Row8: 15

answer will be:
Row1: 1,2,3
Row2: 6,7,8
Row3: 14,15

推荐答案

你不能在任何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


这篇关于如何在一行中选择多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆