我需要一个显示工作站详细信息的数据集,之后我需要确定用于我的报告(SSRS)的前5个,所以我的目标是创建新的top3,它将表示这个并用作图表的过滤器。我意识到我不能对SSRS中的聚合进行过滤,所以我在SQL部分中这样做。
我是用CTE做的,但觉得现代的TSQL可以做得更好,然后用一些线路/运行新功能? (我离它一段时间了)Tx all。这是我的解决方案Tx和节日快乐。我在MSServer 2016上
; WITH cte AS (
SELECT 'St100' St union all select 'St101' St union all select 'St101' St union all select 'St101' St UNION all
SELECT 'St104' St union all select 'St105' St union all select 'St106' St union all select 'St106' St UNION all
SELECT 'St122' St union all select 'St122' St union all select 'St122' St union all select 'St122' St union all
SELECT 'St108' St union all select 'St108' St union all select 'St108' St )
SELECT
cte1.*, cte2.cc ,
CASE wHEN cte2.cc IS NULL THEN 'N' ELSE 'Y' END top3
FROM cte cte1
LEFT JOIN (SELECT TOP 3 St, COUNT(*) cc FROM cte GROUP BY St ORDER BY COUNT(*) desc ) cte2 ON cte2.St = cte1.St
ORDER BY 1
答案 0 :(得分:1)
这样的事情会起作用:
; WITH cte AS (
SELECT 'St100' St union all select 'St101' St union all select 'St101' St union all select 'St101' St UNION all
SELECT 'St104' St union all select 'St105' St union all select 'St106' St union all select 'St106' St UNION all
SELECT 'St122' St union all select 'St122' St union all select 'St122' St union all select 'St122' St union all
SELECT 'St108' St union all select 'St108' St union all select 'St108' St )
SELECT
St
, CAST(CASE WHEN SUM(CASE WHEN L <> St OR L IS NULL THEN 1 ELSE 0 END) OVER (ORDER BY R) < 4 THEN 1 ELSE 0 END AS bit) Top3
FROM
(
SELECT
St
, R
, LAG(St, 1, NULL) OVER (ORDER BY R) L
FROM
(
SELECT
St
, ROW_NUMBER() OVER (ORDER BY C DESC, St) R
FROM
(
SELECT
St
, COUNT(*) OVER (PARTITION BY St) C
FROM cte
) Q
) Q
) Q
ORDER BY St