按最高到最低计数排序列

时间:2016-05-16 14:29:57

标签: sql sql-server-2012

我试图按最高计数频率将[desc]列排序到最低。 [desc]列是推荐位置,例如医院。如果出现了我想要的最多的医院1,那么这个名单就在我的列表顶部,而下一个最高的部分就在那里,等等...

SELECT DISTINCT CASE_NUM,LAST_NAME,FIRST_NAME,UNIT_ID,REF_SOURCE_ID,[DESC]
FROM CDCLIENT
INNER JOIN CDTBL1 ON CDCLIENT.REF_SOURCE_ID = CDTBL1.ID
INNER JOIN CDCLSVC ON CDCLSVC.CLIENT_ID = CDCLIENT.ID
WHERE TYPE = 'REF'
AND STATUS_FLAG = 'A'
ORDER BY [DESC] DESC

2 个答案:

答案 0 :(得分:1)

也许这就是你想要的:

SELECT CASE_NUM, LAST_NAME, FIRST_NAME, UNIT_ID, REF_SOURCE_ID, [DESC]
FROM CDCLIENT INNER JOIN
     CDTBL1
     ON CDCLIENT.REF_SOURCE_ID = CDTBL1.ID INNER JOIN
     CDCLSVC
     ON CDCLSVC.CLIENT_ID = CDCLIENT.ID
WHERE TYPE = 'REF' AND STATUS_FLAG = 'A'
GROUP BY CASE_NUM, LAST_NAME, FIRST_NAME, UNIT_ID, REF_SOURCE_ID, [DESC]
ORDER BY COUNT(*) DESC;

这会进行聚合,然后按计数排序。

答案 1 :(得分:0)

也许这样的东西就是你要找的东西?

SELECT DISTINCT CASE_NUM,
                LAST_NAME,
                FIRST_NAME,
                UNIT_ID,
                REF_SOURCE_ID,
                [DESC],
                COUNT(DISTINCT [DESC]) OVER(PARTITION BY CASE_NUM,
                                                         LAST_NAME,
                                                         FIRST_NAME,
                                                         UNIT_ID,
                                                         REF_SOURCE_ID) As NumberOfDescs
FROM CDCLIENT
INNER JOIN CDTBL1 ON CDCLIENT.REF_SOURCE_ID = CDTBL1.ID
INNER JOIN CDCLSVC ON CDCLSVC.CLIENT_ID = CDCLIENT.ID
WHERE TYPE = 'REF'
AND STATUS_FLAG = 'A'
ORDER BY NumberOfDescs DESC