我有桌子:
Id
,Name
,Account
,Date
,ItemsToSend
Name
和Account
对行进行分组Date
的元素Name
,Account
和ItemsToSend
我管理过这样的事情:
select
Name,
Account,
max(Date),
max(CountItemsSend)
from History
where
Date = (
select max(Date)
from History as p
where
p.Account = History.Account
and p.Name = History.Name
)
group by
Name,
Account
我担心max(Date), max(CountItemsSend)
。我不认为可以。在where
之后,每个组只有1个结果,那么max
在那里使用的意义是什么?
答案 0 :(得分:0)
您不需要聚合。只是:
select h.*
from History h
where h.Date = (select max(h2.Date)
from History h2
where h2.Account = h.Account and
h2.Name = h.Name
);
答案 1 :(得分:0)
另一种可能的方法是使用ROW_NUMBER()
对按name
和account
分组并按date
降序排列的行编号,然后选择编号等于1的行。这些行每组最多Date
,同一行最多CountItemsSend
。
SELECT
t.[Name],
t.[Account],
t.[Date],
t.[CountItemsSend]
FROM (
SELECT
[Name],
[Account],
[Date],
[CountItemsSend],
ROW_NUMBER() OVER (PARTITION BY [Name], [Acount] ORDER BY [Date] DESC) AS Rn
FROM History
) t
WHERE t.Rn = 1
答案 2 :(得分:0)
CTE可以使事情变得更整洁。
WITH maxDates as
(
SELECT Name, Account, MAX(Date) as LatestDate
FROM History
GROUP BY Name, Account
)
SELECT h.Name, h.Account, h.Date, h.CountItemsSend
FROM History h
INNER JOIN maxDates m
on m.Name = h.Name and m.Account = h.Account and m.LatestDate = h.Date