这可能很容易,但对于我的生活,我似乎无法弄明白。
这是我的表:
Date User Amount
---------- ----- ------
01/01/2010 User1 2
01/01/2010 User2 2
01/01/2010 User1 4
01/01/2010 User2 1
01/02/2010 User2 2
01/02/2010 User1 2
01/02/2010 User2 4
01/02/2010 User2 1
过去几个月。我需要得到以下结果:
Date User Amount
---------- ----- ------
01/01/2010 User1 6
01/02/2010 User2 7
基本上,每天都有Max(SUM(Amount))
的用户。
我很感激你们提供的任何暗示。
感谢。
答案 0 :(得分:2)
SELECT MAX(amt),`Date`,`User` FROM
(SELECT SUM(`Amount`),`Date`,`User` as amt .... GROUP BY `Date`,`User`)
GROUP BY `Date`
答案 1 :(得分:1)
select t.*
from (
select Date, Max(Amount) as MaxAmount
from MyTable
group by Date
) tm
inner join MyTable t on tm.Date = t.Date and tm.MaxAmount = t.Amount
注意:如果在给定的一天有两个用户具有相同的最大金额,这将为您提供两个用户记录。
答案 2 :(得分:0)
我实际上最终选择了以下内容:
WITH ranked AS
(
SELECT ROW_NUMBER() OVER (ORDER BY SUM(Amount), Date, User) as 'rank', SUM(Amount) AS Amount, User, Date FROM MyTable GROUP BY Date, User
)
SELECT Date, User, Amount
FROM ranked
WHERE rank IN ( select MAX(rank) from ranked group by Date)
ORDER BY Date DESC
答案 3 :(得分:0)
使用RANK ... OVER
可以更简洁,但以下是直接的解决方案:
WITH summary_user_date
AS (SELECT Date, User, SUM(Amount) AS SumAmount
FROM MyTable
GROUP BY Date, User
)
, summary_date
AS (SELECT Date, MAX(SumAmount) AS SumAmount
FROM summary_user_date
GROUP BY Date
)
SELECT summary_user_date.*
FROM summary_user_date
INNER JOIN summary_date
ON summary_date.Date = summary_user_date.Date
AND summary_date.SumAmount = summary_user_date.SumAmount
应该提到的是,如果多于一个用户具有相同的最大金额,则将显示所有这些用户。如果不需要,那么应该使用基于RANK
的解决方案。
答案 4 :(得分:0)
使用CTE可以执行以下操作:
With DailyTotals As
(
Select [Date], [User], Sum(Amount) As Total
From #Test
Group By [Date], [User]
)
Select [Date],[User],Total
From DailyTotals As DT
Where Total = (
Select Max(Total)
From DailyTotals As DT1
Where DT1.[Date] = DT.[Date]
)
Order By DT.[Date]
非CTE解决方案将是:
Select [Date],[User],Total
From (
Select [Date], [User], Sum(Amount) As Total
From #Test
Group By [Date], [User]
) As DT
Where DT.Total = (
Select Max(DT1.Total)
From (
Select [Date], [User], Sum(Amount) As Total
From #Test
Group By [Date], [User]
) As DT1
Where DT1.[Date] = DT.[Date]
)
Order By DT.[Date]