如何选择每天最大计数的用户

时间:2011-09-13 00:45:56

标签: sql sql-server

我有一个包含三列的表

UserID,Count,Date

我希望能够为每个日期选择计数最多的用户ID。

我已尝试使用内联选择语句进行一些不同的查询变体,但没有一个使用100%,我不太喜欢使用三个内联选择的选择。

内联是否选择了不使用临时表的唯一方法?什么是解决这个问题的最佳方法?

4 个答案:

答案 0 :(得分:2)

如果Count中有一个平局但是应该有效,这个解决方案会给你多条记录。

SELECT a.Date, a.UserId, a.[Count]
FROM yourTable a INNER JOIN (
  SELECT MAX([Count]) as [Count], Date
  FROM yourTable
  GROUP BY Date
) b ON a.[Count] = b.[Count] AND a.Date = b.Date
ORDER BY a.Date

答案 1 :(得分:1)

如果[Date]实际上是没有时间组件的[Date]列:

;WITH x AS
(
  SELECT [Date], [Count], UserID, rn = ROW_NUMBER() OVER
    (PARTITION BY [Date] ORDER BY [Count] DESC)
    FROM dbo.table
)
SELECT [Date], [Count], UserID
FROM x
WHERE rn = 1
ORDER BY [Date];

如果[Date]是带有时间组件的DATETIME列,则:

;WITH x AS
(
  SELECT [Date] = DATEADD(DAY, DATEDIFF(DAY, '19000101', [Date]), '19000101'), 
    [Count], UserID, rn = ROW_NUMBER() OVER
    (PARTITION BY DATEADD(DAY, DATEDIFF(DAY, '19000101', [Date]), '19000101')
       ORDER BY [Count] DESC)
    FROM dbo.table
)
SELECT [Date], [Count], UserID
FROM x
WHERE rn = 1
ORDER BY [Date];

如果您想在平局时挑选特定行,可以在结尾处的ORDER BY添加平局。如果您想在关联的情况下包含多行,可以尝试将ROW_NUMBER()更改为DENSE_RANK()

答案 2 :(得分:1)

SELECT x.*
FROM (
  SELECT Date
  FROM atable
  GROUP BY Date
) t
CROSS APPLY (
  SELECT TOP 1 WITH TIES
    UserID, Count, Date
  FROM atable
  WHERE Date = t.Date
  ORDER BY Count DESC
) x

如果Datedatetime类型并且可以包含非零时间组件,请更改t表,如下所示:

…
FROM (
  SELECT Date = DATEADD(DAY, DATEDIFF(DAY, 0, Date), 0)
  FROM atable
  GROUP BY DATEADD(DAY, DATEDIFF(DAY, 0, Date), 0)
) t
…

参考文献:

答案 3 :(得分:0)

for SQL 2k5

select UserID, Count, Date
from tb
where Rank() over (partition by Date order by Count DESC, UserID DESC) = 1