T-SQL查询帮助 - 查找表中的范围

时间:2016-09-13 11:06:02

标签: sql sql-server tsql

我有一张桌子如下。我需要在下面提到的名称范围内的结果。请提供T-SQL查询

ID  Name
101 AA1
102 AA1
103 AA1
104 AA2
105 AA2
106 AA3
107 AA1
108 AA1
109 AA2
110 AA2
111 AA2
112 AA4

需要结果

Name Range
AA1  101-103
AA2  104-105
AA3  106
AA1  107-108
AA2  109-111
AA4  112

3 个答案:

答案 0 :(得分:3)

您可以使用行号方法的差异来执行此操作:

select name, min(id), max(id)
from (select t.*,
             row_number() over (order by id) as seqnum,
             row_number() over (partition by name order by id) as seqnum_n
      from t
     ) t
group by name, (seqnum - seqnum_n);

解释这是如何工作有点困难。对于具有连续ID的名称,行号的差异是不变的。如果您运行子查询,您将看到行号的样子以及差异与您想要的差异。

答案 1 :(得分:1)

只需使用concat with group by:

SELECT NAME, CONCAT(MIN(id), '-', MAX(id)) range
FROM Table1
GROUP BY NAME

答案 2 :(得分:0)

与Statement,PARTITION BY和Group By

一起使用
;WITH T
     AS (SELECT *,
                ID - ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [ID]) AS Grp
         FROM   @tbl1)
SELECT [Name],
       CAST(MIN(Id) AS VARCHAR(5))+'-'+CAST(MAX(Id) AS VARCHAR(5)) AS Range
FROM   T
GROUP  BY [Name],
          Grp
ORDER  BY MIN(ID)