我有这张桌子:
Month Year Provider Number
1 2015 1 345
2 2015 1 345
3 2015 1 345
12 2015 2 444
1 2016 2 444
假设我想通过提供商获得所有不同的数字,但只有最大月份和最大年份,如下所示:
Month Year Provider Number
3 2015 1 345
1 2016 2 444
我有这个丑陋的查询,我想改进:
SELECT (SELECT max([Month])
FROM dbo.Info b
WHERE b.Provider = a.Provider
AND b.Number = a.Number
AND [Year] = (SELECT max([Year])
FROM dbo.Info c
WHERE c.Provider = a.Provider
AND c.Number = a.Number)) AS [Month],
(SELECT max([Year])
FROM dbo.Info d
WHERE d.Provider = a.Provider
AND d.Number = a.Number)) AS [Year],
a.Provider,
a.Number
FROM dbo.Info a
答案 0 :(得分:1)
一种选择是使用row_number
:
select *
from (
select *, row_number() over (partition by provider
order by [year] desc, [month] desc) rn
from dbo.Info
) t
where rn = 1
这假设数字和提供者字段相同。如果没有,您可能还需要按数字字段进行分区。
答案 1 :(得分:0)
您可以使用row_number和cte
;WITH cte AS (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Provider ORDER BY [Year] DESC, [Month] DESC) as rNum
FROM Info)
SELECT *
FROM cte where rNum = 1
如果您想创建视图,那么
CREATE VIEW SomeViewName
AS
WITH cte AS (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Provider ORDER BY [Year] DESC, [Month] DESC) as rNum
FROM Info)
SELECT *
FROM cte where rNum = 1