2012-12-07 49 views
3

我有一個查詢從列表1有重複記錄的表中返回數據,但其他列中可能有不同的值。我希望僅使用標準選擇正確的記錄,將第1列中每個值的記錄帶入一個視圖。在sql視圖中刪除重複的記錄

這是查詢;

SELECT 
    PrimaryColumn1, 
    Column2, 
    Column3, 
    Date1, 
    Date2 
FROM 
    My_Table 

我想在我基礎上Date1最新日期創建視圖在PrimaryColumn1唯一不同的值,如果這是一個重複的,以及在日期2。

我試着做以下,但沒有能夠使它發揮作用

SELECT 
    PrimaryColumn1, 
    Column2, 
    Column3, 
    Date1, 
    Date2 
FROM  
    (SELECT 
     [PrimaryColumn1, 
     Column2, 
     Column3, 
     Date1, 
     Date2, 
     ROW_NUMBER() OVER(PARTITION BY [Date1] ORDER BY Date2) AS RowNumber 
    FROM  
     My_Table) 
WHERE 
    RowNumber = 1 

任何幫助將不勝感激。

下面的建議後,最終查詢這個樣子:

SELECT 
    PrimaryColumn1, 
    Column2, 
    Column3, 
    Date1, 
    Date2 
FROM  
    (SELECT 
     [PrimaryColumn1, 
     Column2, 
     Column3, 
     Date1, 
     Date2, 
     ROW_NUMBER() OVER(PARTITION BY PrimaryColumn1 
          ORDER BY Date1 DESC, Date2 DESC) AS RowNumber) data 
WHERE 
    RowNumber = 1 

回答

1

我覺得你ROW_NUMBER()說法應該是這樣的:

ROW_NUMBER() OVER(PARTITION BY PrimaryColumn1 
         ORDER BY Date1 DESC, Date2 DESC) AS RowNumber 

既然你正在尋找的最新記錄對於每個PrimaryColumn1值,這應該做你想做的(據我所知)。

+0

這就像一個魅力。優秀。謝謝。 – user1886816

0
SELECT 
    PrimaryColumn1, 
    Column2, 
    Column3, 
    Date1, 
    Date2 
FROM My_Table 
INNER JOIN 
    (SELECT PrimaryColumn1, 
     MAX(Date1) AS max_Date1, 
     MAX(Date2) AS max_Date2, 
     FROM My_Table 
     GROUP BY PrimaryColumn1 
    ) AS Maxes 
ON Maxes.PrimaryColumn1 = My_Table.PrimaryColumn1 
AND Maxes.max_Date1 = My_Table.Date1 
AND Maxes.max_Date2 = My_Table.Date2 
+0

感謝您的幫助 – user1886816

1

CROSS APPLY是一個很好的方式來做這樣的事情。例如,這會爲「產品」表中的每個CategoryID拉出一條記錄,並顯示每個類別中最昂貴產品的產品數據。

這有效地爲您提供了一種在聯接中使用相關子查詢的方法。很酷。

USE Northwind; 
GO 
--Get a distinct list of CategoryID values 
--From the dbo.Products table, and show the 
--Product details for the most expensive product 
--in each of those categories.... 
SELECT DISTINCT 
    Prod.CategoryID, 
    TopProd.ProductID, 
    TopProd.ProductName, 
    TopProd.UnitPrice 
FROM dbo.Products AS Prod 
CROSS APPLY 
(
    --Find the top 1 product in each category by unitprice 
    SELECT TOP 1 
    ProductID, 
    ProductName, 
    UnitPrice 
    FROM dbo.Products 
    --This is the "correlated" part where 
    --we filter by the outer queries' CategoryID 
    WHERE CategoryID = Prod.CategoryID 
    --The ORDER BY determines which product 
    --you see for each category. In this 
    --case I'll get the most expensive product 
    ORDER BY UnitPrice DESC 
) AS TopProd; 
+0

感謝您的幫助 – user1886816