组中COUNT的SQL Server MAX

时间:2016-03-01 15:33:21

标签: sql-server greatest-n-per-group

所以我在下面的SQL代码中遇到了问题(我还不熟悉SQL,所以我可能做错了)。现在我希望能够计算一个Emp_ID出现在Cust_ID旁边的次数,然后只显示出现最多的Emp_ID。

Temp table #RAttP 

|CUST_ID | EMP_NAME | EMP_ID | SOMETHING1 | SOMETHING2 |
|:------:|:--------:|:------:|:----------:|:----------:|
| 1      |   John   |   100  |     w/e    |     w/e    |
| 1      |   John   |   100  |     w/e    |     w/e    |
| 1      |   Jane   |   200  |     w/e    |     w/e    |
| 2      |   Jane   |   200  |     w/e    |     w/e    |

回答我正在寻找:

|CUST_ID | EMP_NAME | EMP_ID |
|:------:|:--------:|:------:|
| 1      |   John   |   100  | 
| 2      |   Jane   |   200  |

我的代码:

SELECT FL2.CUST_ID
       ,#RAttP.EMP_NAME
       ,#RAttP.EMP_ID
       ,FL2.MostSeen
    FROM #RAttP
        INNER JOIN
        (SELECT DISTINCT FL1.CUST_ID
               ,MAX(FL1.AmtSeen) AS MostSeen
            FROM (SELECT #RAttP.CUST_ID
                   ,#RAttP.EMP_NAME
                   ,#RAttP.EMP_ID
                   ,COUNT(EMP_ID) AS AmtSeen
                        FROM #RAttP
                        GROUP BY #RAttP.CUST_ID, #RAttP.EMP_NAME, #RAttP.EMP_ID
                 ) FL1
            GROUP BY FL1.CUST_ID
        )FL2
        ON FL2.CUST_ID = #RAttP.CUST_ID
    GROUP BY FL2.MostSeen, FL2.CUST_ID, #RAttP.EMP_NAME, #RAttP.EMP_ID
    ORDER BY FL2.CUST_ID

2 个答案:

答案 0 :(得分:0)

您可以使用窗口功能:

SELECT CUST_ID, EMP_NAME, EMP_ID
FROM (
  SELECT CUST_ID, EMP_NAME, EMP_ID, 
         ROW_NUMBER() OVER (PARTITION BY CUST_ID ORDER BY cnt DESC) AS rn
  FROM (
    SELECT CUST_ID, EMP_NAME, EMP_ID,
         COUNT(EMP_ID) OVER (PARTITION BY CUST_ID, EMP_ID) AS cnt
    FROM RAttP ) AS t) AS s
WHERE s.rn = 1
COUNT分区上的OVER子句一起使用的

CUST_ID, EMP_ID会返回Emp_ID旁边显示Cust_ID的次数。第二级查询在OVER窗口函数的ROW_NUMBER子句中使用此计数,以确定具有最大Emp_ID个出现次数的记录。

答案 1 :(得分:0)

这可以解决您的问题:

SELECT          * 
FROM 
(
    SELECT          *, rank() OVER (PARTITION BY cust_id ORDER BY cnt DESC) AS rank
    FROM 
    (
        SELECT          cust_id, emp_id, count(1) as cnt
        FROM            #RAttP
        GROUP BY        cust_id, emp_id
    ) AS a
) AS B 
WHERE b.rank=1