【问题标题】:TSQL advanced, check rating of record count on the flyTSQL 高级,即时检查记录数的评级
【发布时间】:2017-12-12 00:08:32
【问题描述】:

我需要一个显示站点详细信息的数据集,稍后我需要确定用于我的报告 (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

【问题讨论】:

  • 所以你得到了你想要的,但需要使用更好的SQL来获得类似的输出?
  • Tx VikingG,是的,我认为这应该是一些新功能,以避免额外的步骤,

标签: sql-server tsql reporting-services


【解决方案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

【讨论】:

  • Tx 克里斯的想法!
猜你喜欢
  • 2022-09-28
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
  • 2022-10-29
  • 1970-01-01
相关资源
最近更新 更多