我需要创建查询以从相同记录中选择MAX
日期列记录。我正在使用此查询,但它返回相同的记录
SELECT DISTINCT SID, Id, MAX(ExpireDate) FROM tblPayers GROUP BY id,SID,ExpireDateEn
但我得到的结果是:
SID Id ExpireDate
2 3 5/25/2017
3 12 6/27/2017
1 13 5/28/2017
1 14 6/27/2017
答案 0 :(得分:0)
只需从分组中删除ExpireDate,也可以从查询中删除,因为这也不是必需的: -
Select distinct SID, id, ExpireDate
from tblPayers a
inner join
(
select SID,MAX(ExpireDate) as dt
from tblPayers
group by SID
) b
on a.SID=b.SID and a.ExpireDate=b.dt
答案 1 :(得分:0)
基于对另一个答案的评论(“它返回2个相同的SID,我只需要返回一个最大SID记录”)我猜你只想要每个SID的最新记录,返回所有其他专栏。
为此,您可以使用ROW_NUMBER()
:
SELECT p.ID,
p.[SID],
p.[ExpireDate]
FROM ( SELECT p.ID,
p.[SID],
p.[ExpireDate],
RowNum = ROW_NUMBER() OVER(PARTITION BY p.[SID]
ORDER BY p.[ExpireDate] DESC)
FROM dbo.tblPayers AS p
) AS p
WHERE p.RowNum = 1;
答案 2 :(得分:0)
with tablecte(sid,expiredate)
as
(
select SID , Max(ExpireDate)
from tblPlayers
group by SID
)
select tp.SID,tp.Id,tp.ExpireDate from tblPlayers tp join tablecte tc
on tp.SID = tc.sid and tp.Expiredate = tc.expiredate