尝试从最高频率计数到最低频率的列

时间:2016-05-12 15:41:44

标签: sql sql-server-2012

我已经尝试了强制转换,而over分区在底部注释掉了代码。我希望首先以最高计数排序[DESC]列。

--DROP TABLE #REF

SELECT DISTINCT CASE_NUM,LAST_NAME,FIRST_NAME,UNIT_ID,REF_SOURCE_ID,[DESC]
--INTO #REF
FROM CDCLIENT
INNER JOIN CDTBL1 ON CDCLIENT.REF_SOURCE_ID = CDTBL1.ID
INNER JOIN CDCLSVC ON CDCLSVC.CLIENT_ID = CDCLIENT.ID
WHERE TYPE = 'REF'
ORDER BY CAST([DESC],CASE_NUM,LAST_NAME,FIRST_NAME,UNIT_ID,REF_SOURCE_ID as                                     
INTEGER) DESC


--SELECT R.*,
--       COUNT(*) OVER (PARTITION BY CDTBL1.[DESC]) as COUNTS,
--FROM #REF R;

2 个答案:

答案 0 :(得分:0)

只需对所需的每个排序子句使用ORDER BY [DESC] desc,CASE_NUM desc等...

答案 1 :(得分:0)

试试这个:

SELECT  CASE_NUM ,
        LAST_NAME ,
        FIRST_NAME ,
        UNIT_ID ,
        REF_SOURCE_ID ,
        [DESC]
FROM    ( SELECT    CASE_NUM ,
                    COUNT(CASE_NUM) AS CASE_NUM_Count ,
                    LAST_NAME ,
                    COUNT(LAST_NAME) AS LAST_NAME_Count ,
                    FIRST_NAME ,
                    COUNT(FIRST_NAME) AS FIRST_NAME_Count ,
                    UNIT_ID ,
                    COUNT(UNIT_ID) AS UNIT_ID_Count ,
                    REF_SOURCE_ID ,
                    COUNT(REF_SOURCE_ID) AS REF_SOURCE_ID_Count ,
                    [DESC] ,
                    COUNT([DESC]) AS DESC_Count
--INTO #REF
          FROM      CDCLIENT
                    INNER JOIN CDTBL1 ON CDCLIENT.REF_SOURCE_ID = CDTBL1.ID
                    INNER JOIN CDCLSVC ON CDCLSVC.CLIENT_ID = CDCLIENT.ID
          WHERE     TYPE = 'REF'
          GROUP BY  CASE_NUM ,
                    LAST_NAME ,
                    FIRST_NAME ,
                    UNIT_ID ,
                    REF_SOURCE_ID ,
                    [DESC]
        ) AS InnerLoop
ORDER BY InnerLoop.DESC_Count ,
        InnerLoop.CASE_NUM_Count ,
        InnerLoop.LAST_NAME_Count ,
        InnerLoop.FIRST_NAME_Count ,
        InnerLoop.UNIT_ID_Count ,
        InnerLoop.REF_SOURCE_ID_Count DESC;