如何实现MAX(COUNT(columnName))

时间:2016-02-09 11:43:52

标签: sql-server tsql aggregate-functions

我有以下表格列:

CommunicationNumber, DayOfWeekSlot, TwoHourSlot

我想计算CommunicationNumberDayOfWeekSlot相同的每个TwoHourSlot的行数。从这个结果我想选择(DayOfWeekSlot/TwoHourSlot)的计数最高的行。

我写了以下查询:

SELECT tblLog.CommunicationNumber, MAX(tblLog.Priority) AS Frequency, tblLog.DayOfWeekSlot, tblLog.TwoHourSlot
FROM (SELECT CommunicationNumber, Count(*) AS Priority, DayOfWeekSlot, TwoHourSlot 
        FROM Miafon.dbo.tblPhoneLogRep
        WHERE CallDuration > 0
        GROUP BY CommunicationNumber, DayOfWeekSlot, TwoHourSlot) tblLog
GROUP BY tblLog.CommunicationNumber, tblLog.DayOfWeekSlot, tblLog.TwoHourSlot
ORDER BY tblLog.CommunicationNumber, Frequency DESC

以上查询为我提供了以下列:

CommunicationNumber, Frequency, DayOfWeekSlot, TwoHourSlot

由于我按CommunicationNumberTwoHourSlotDayOfWeekSlot进行分组,因此我得到这些值不同的所有行(按频率的降序排序)。我只想要具有最高频率值的行。

我如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

你可以像这样使用row_number:

SELECT * FROM (
    SELECT tblLog.CommunicationNumber, tblLog.Priority AS Frequency, tblLog.DayOfWeekSlot, tblLog.TwoHourSlot
    ,row_number() OVER (PARTITION BY tblLog.CommunicationNumber order by tblLog.Priority desc) as rnk
    FROM (SELECT CommunicationNumber, Count(*) AS Priority, DayOfWeekSlot, TwoHourSlot 
          FROM Miafon.dbo.tblPhoneLogRep
          WHERE CallDuration > 0
          GROUP BY CommunicationNumber, DayOfWeekSlot, TwoHourSlot) tblLog)
WHERE rnk = 1