表1如下:
Name Number Month Year Fee_Paid
Ravi 1 1 2010 100
Raju 2 1 2010 200
Kumar 3 1 2010 300
Ravi 1 2 2011 100
Raju 2 2 2011 200
Kumar 3 2 2011 300
Ravi 1 3 2012 100
Raju 2 3 2012 200
Kumar 3 3 2012 300
结果应如下:
Name Number Month Year Fee_Paid
Ravi 1 3 2012 100
Raju 2 3 2012 200
Kumar 3 3 2012 300
结果应显示最新的年份和月份,包括该期间的姓名,编号和费用。请帮助我。
答案 0 :(得分:1)
如果你想要每个名字的最后一行,不管上个月他们的是哪个月:
;WITH x AS
(
SELECT Name, Number, [Month], [Year], [Fee_Paid],
rn = ROW_NUMBER() OVER
(PARTITION BY Name ORDER BY [Year] DESC, [Month] DESC)
FROM dbo.Table1
)
SELECT Name, Number, [Month], [Year], [Fee_Paid]
FROM x
WHERE rn = 1
ORDER BY Number;
如果您希望找到上一年/月组合中的所有行,无论名称如何,查询只会略有不同:
;WITH x AS
(
SELECT Name, Number, [Month], [Year], [Fee_Paid],
rn = DENSE_RANK() OVER (ORDER BY [Year] DESC, [Month] DESC)
FROM #x
)
SELECT Name, Number, [Month], [Year], [Fee_Paid]
FROM x
WHERE rn = 1
ORDER BY Number;
这两个查询都给出了你似乎想要的结果,但其中一个可能只是巧合才是正确的。
答案 1 :(得分:1)
这是非CTE解决方案:
select HighestYear.* from (
select v1.* from visitors v1
left join visitors v2
on v1.number = v2.number and v1.year < v2.year
where v2.year is null
) HighestYear
left join visitors v3
on HighestYear.number = v3.number and HighestYear.year = v3.year
and HighestYear.month < v3.month
where v3.month is null
答案 2 :(得分:0)
SELECT
Details.Name,
Details.Number,
Details.Month,
Details.Year,
Details.Fee_Paid
FROM
(
SELECT
Name,
MAX(Year) AS Year,
MAX(Month) AS Month
) AS MaxValues
INNER JOIN MyTable AS Details ON
Details.Name = MaxValues.Name
AND Details.Year = MaxValues.Year
AND Details.Month = MaxValues.Month