通过范围和值sql查询分组值

时间:2018-01-03 07:12:58

标签: sql-server sorting filter grouping

我有两张桌子。 表1有以下字段。

From    To      id
----    ----     ----
  0      0        1
  1      5        2
  5      10       3
  10     15       4 

表2:

Table 1 ID    Value
---------     -------
1              10
2              10
3              15
4              10

当前输出:

from      To     Value
-----  ------   -------
0         15      10
5         10      15

必需的输出

From     To     Value
------   ----   ------ 
0         5      10
5         10     15
10        15     10

如何获得输出

SELECT  MIN(DiscountFrom) FromDiscount ,
    MAX(DiscountTo) Todiscount ,
    Amount
FROM    table1 t1
    JOIN table2  t2 ON t1.id =  t2.id
GROUP BY Amount

2 个答案:

答案 0 :(得分:0)

这里对我来说分组没有意义,如果找到0,我用lead()函数来访问下一条记录

select distinct 
       case when t.[from] = 1 then 0 else t.[from] end [from],  
       case when t.[to] = 0 then lead(t.[to]) over (order by t.id) else t.[to] end [to], 
       t1.value 
from table1 t
join table2 t1 on t1.id = t.id

结果:

from    to  value
0       5   10
5      10   15
10     15   10

答案 1 :(得分:0)

看起来您的数据不一致,为此我必须将第一条记录更改为

From    To      id
----    ----     ----
  0      1        1 

然后这适用于所有情况

;WITH test1
     AS (SELECT
           t.id
           ,[from]
           ,[to]
           ,value
         FROM
           table1 t
           JOIN table2 t1
             ON t1.id = t.id),
     MyTest
     AS (SELECT
           Anchor.[from]
           ,Anchor.[To]
           ,Anchor.value
           ,1 AS Grp
         FROM
           test1 AS Anchor
         WHERE
           [From] = 0
         UNION ALL
         SELECT
           Child.[from]
           ,Child.[To]
           ,Child.value
           ,CASE WHEN Mytest.value = child.value THEN 0 ELSE 1 END + MyTest.Grp AS grp
         FROM
           test1 AS Child
           INNER JOIN MyTest
                   ON Mytest.[To] = child.[From])
SELECT
  Min([From]) AS [From]
  ,Max([To])  AS [To]
  ,Max(Value) AS Value
FROM
  mytest
GROUP  BY
  Grp