2016-02-18 35 views
1

我有這個表:獲得分離柱最大日期(年,月)

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

是否與您查詢的是什麼? – dfundako

+0

如果可能,我會強烈建議將日期時間信息存儲在單個日期時間列中。將其存儲在兩列中非常具有挑戰性。當然這並不總是可能的。 –

回答

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 
+0

好吧,讓我們說我需要一個視圖,我想用這個,我應該創建一個內聯函數,我猜,在這種情況下,性能仍然很好? – carlosm

+0

您可以使用cte創建視圖。不需要內聯功能。 – SQLChao

+0

@carlosm添加了如何使用cte創建視圖。 – SQLChao

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 

這假設數字和提供者字段是相同的。如果不是,您可能還需要按數字字段進行分區。

相關問題