我有一张桌子
DPN Incidents wk32 wk31 wk30 wk29
15326868 2.00 16,020.98 9,586.14
13655518 2.00 15,246.40 2,619.89
13592065 4.00 4,138.67 7,851.41 7,725.56 7,593.11
13968309 4.00 3,027.89 3,788.18 10,155.71 2,328.68
13533086 4.00 10,266.52 6,479.47 8,761.08 10,949.50
13838079 3.00 5,890.04 1,214.42 10,445.45
如果他们输入topx = 2
我的输出应为
DPN # of Incidents wk32 wk31 wk30 wk29
15326868 2.00 16,020.98 9,586.14
13655518 1.00 15,246.40
13592065 1.00 7,851.41
13968309 1.00 10,155.71
13533086 2.00 8,761.08 10,949.50
13838079 1.00 10,445.45
以上输出是应该每周按desc排序并以与上面相同的格式显示,并重新计算事件数。 事件是每个值的列数。 请告诉我如何做到这一点。
答案 0 :(得分:1)
这有几件事。第一种是使用row_number()
来识别每周的前两名。第二个是将值限制为这两个,第三个是重新计算incidents
:
select DPN,
sum((case when wk32 is not null then 1 else 0 end) +
(case when wk31 is not null then 1 else 0 end) +
(case when wk30 is not null then 1 else 0 end) +
(case when wk29 is not null then 1 else 0 end)
) as incidents,
wk32, wk31, wk30, wk29
from (select DPN,
(case when seqnum_wk32 <= 2 then wk32 end) as wk32,
(case when seqnum_wk31 <= 2 then wk32 end) as wk31,
(case when seqnum_wk30 <= 2 then wk32 end) as wk30,
(case when seqnum_wk29 <= 2 then wk32 end) as wk29
from (select t.*,
row_number() over (order by wk32 desc) as seqnum_wk32,
row_number() over (order by wk31 desc) as seqnum_wk31,
row_number() over (order by wk30 desc) as seqnum_wk30,
row_number() over (order by wk29 desc) as seqnum_wk29
from t
) t
) t
order by wk32 desc, wk31 desc, wk30 desc, wk29 desc;