SQL Group By Max of Group By Count

时间:2013-03-22 06:49:11

标签: sql count max

这是我的初始计数查询和结果集。我只是不知道如何让最大查询工作。

查询

SELECT QM_CUST_CODE, QM_XX_REGION, COUNT(QM_QUOTE_NUM) as Quotes
FROM QM (NOLOCK)
WHERE QM_CUST_CODE in ('H-PAT001', 'H-ABI002')
GROUP BY QM_CUST_CODE, QM_XX_REGION

结果

QM_CUST_CODE    QM_XX_REGION    Quotes
1  H-ABI002     0           1
2  H-PAT001     0           3
3  H-ABI002     1           397
4  H-PAT001     1           1509
5  H-PAT001     2           1

- 问题 如何只返回第3行和第4行,因为这些是按区域划分的客户代码,其中MAX没有引号。

2 个答案:

答案 0 :(得分:0)

WITH recordsList
AS
(
    SELECT  QM_CUST_CODE, QM_XX_REGION, COUNT(QM_QUOTE_NUM) as Quotes,
            DENSE_RANK() OVER  (PARTITION BY QM_CUST_CODE 
                                ORDER BY COUNT(QM_QUOTE_NUM) DESC) rn
    FROM    QM
    WHERE   QM_CUST_CODE in ('H-PAT001', 'H-ABI002')
    GROUP   BY QM_CUST_CODE, QM_XX_REGION
)
SELECT  QM_CUST_CODE, QM_XX_REGION, Quotes
FROM    recordsList
WHERE   rn = 1

答案 1 :(得分:0)

如果您只想获得两行具有最高报价数,请尝试以下方法:

Select Top 2 * From
(
SELECT QM_CUST_CODE, QM_XX_REGION, COUNT(QM_QUOTE_NUM) as Quotes
FROM QM
WHERE QM_CUST_CODE in ('H-PAT001', 'H-ABI002')
GROUP BY QM_CUST_CODE, QM_XX_REGION
)tbl
Order By  Quotes Desc