t-sql对范围之间的行进行分组

时间:2014-06-07 10:55:37

标签: sql-server sql-server-2008 tsql

我有此查询返回基于数量的折扣列表

with cte([item code],price,discount,rngLow,rngHigh,id) as

    (
    select 'xxx-xxxxxxx' as [item code],l.t$pric,l.t$disc,lqanp=l.t$qanp,hqanp=h.t$qanp,id = row_number() over(partition by h.t$qanp order by h.t$qanp) from EdiCatalog l
    join ediCatalog h on l.comno=h.comno and l.t$cpls=h.t$cpls and  l.t$cuno=h.t$cuno and h.t$item=l.t$item  and l.t$qanp < h.t$qanp 

     where l.comno=@comno and l.t$cpls=@cpls and l.t$cuno=@cuno  
    )
    select * from cte

返回结果集

enter image description here

如何将结果集转换为此

enter image description here

2 个答案:

答案 0 :(得分:1)

你可以从这开始:

SELECT *
FROM cte a
WHERE rngHigh=(
  SELECT MIN(rngHigh)
  FROM cte b
  WHERE b.rngLow=a.rngLow
)

这会给你这个结果集:

discount    rngLow  rngHigh
40            1       9
68            9      23
73           23      47
75           47     299

答案 1 :(得分:0)

@Frazz, 这就是我现在拥有的 enter image description here

对你的建议几乎没有改动..

SELECT rngLow=case rngLow 
                                        when 1 then rnglow
                                        else rnglow+1 end,rngHigh,discount,id
FROM cte a
WHERE rngHigh=(
  SELECT MIN(rngHigh)
  FROM cte b
  WHERE b.rngLow=a.rngLow
)