[英]SQL SERVER How to take each group by as an alias
我想計算表中所有值> = 10的列。這是我的表:
Date##### | Value1 | Value2 | Value3 | Type 23/04/2014 | 1,2 | 12,3 | 10 | Alert 23/04/2014 | 11,2 | 3 | 10,3 | Alert 24/04/2014 | 10,9 | 3 | 1 | Non-Alert
我想將每個按列類型的分組作為別名,例如:GROUP BY Type ='Alert'作為TAlert,Group BY Type ='Non-Alert作為TNon-Alert'。
假設我有很多日期組,我希望它僅顯示最后三個日期組。
到目前為止,這是我的代碼:
select d, cnt
from (
select top 3 [Date] as d,
sum( Case When value1 >= 10 then 1 else 0 end
+ Case When Value2 >= 10 then 1 else 0 end
) as cnt
from tbBooth
GROUP BY [Date],[Type]
Order By [Date] DESC
) x
ORDER BY d ASC
反正有怎么做呢? 因為我想將其放在我的折線圖系列中(系列1中的TAlert和系列2中的TNon-Alert)。 這是我表中查詢的結果,
> d表示日期,cnt表示計數
d | Type | cnt 23/04/2014 | Non-Alert | 8 24/04/2014 | Alert | 3 24/04/2014 | Non-Alert | 7
然后,我想采用列類型中的每個組。 例如,警報組為TAlert,或非警報組為TNon-Alert...。
在此先感謝...。
您需要先取消PIVOT,然后再與CASE求和。 我不確定“僅最后3組日期”適合什么地方,也許更完整的示例數據會有所幫助。
但是,根據現在的情況,嘗試以下操作:
;with x as (
select *
from (
select [date], [type], Value1, Value2, Value3
from tbBooth
) p
unpivot (
v for val in (Value1, Value2, Value3)
) as up
)
select [date], [type], sum(case when v >= 10 then 1 else 0 end)
from x
group by [date], [type]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.