2015-10-14 90 views
1

我有類別和產品表。我想根據類別在一行中記錄具有最大日期的產品的記錄。如果根本沒有產品,我至少想要展示這個類別。產品的ID將爲NULL,因爲一旦沒有記錄,ProductDate也將爲NULL。按日期加入MAX記錄並加入另一張表

我試過這個腳本,我什麼也沒得到(我沒有一個作爲@ID傳遞的類別的產品)。如果我將INNER JOIN更改爲LEFT JOIN,我將獲得所有類別幷包含所有最大產品。因爲我用的ID過濾,我應該得到的只是一個記錄

SELECT c.ID AS CategoryID, 
     p.ID AS ProductID, 
     p.Date AS ProductDate, 
FROM Category c 
LEFT JOIN Product p 
ON c.ID = p.CategoryID 
INNER JOIN 
    (
     SELECT CategoryID, MAX(Date) AS MaxDate 
     FROM Product 
     WHERE CategoryID = @ID 
     GROUP BY CategoryID 
    ) p2 
    ON p.CategoryID = p2.CategoryID 
WHERE c.ID = @ID 
ORDER BY p.CategoryID, p.Date 

我該怎麼做才能得到一個記錄將匹配與類別超過產品(因爲我沒有任何產品類別)?

例如

Category 
C1 Cat1 
C2 Cat2 

Product 
P1 Cat1 Prod1 2015-01-01 ... 
P2 Cat1 Prod2 2015-10-01 ... 
P3 Cat1 Prod1 2015-10-14 ... 

Result 
@ID = C2 (Category.ID) 

CategoryID, ProductID, Date 
C2, NULL, NULL 

Result 
@ID = C1 

CategoryID, ProductID, Date 
C1, P3, 2015-10-14 

UPDATE

我發現了錯誤,因爲我並沒有完全發佈問題。我這樣做additionaly

WHERE c.ID = @ID 
AND c.Inactive IS NULL OR (c.Inactive = 0) 
ORDER BY p.CategoryID, p.Date 

我改這個來解決這個問題

WHERE c.ID = @ID 
AND (c.Inactive IS NULL OR c.Inactive = 0) 
ORDER BY p.CategoryID, p.Date 

但Giorgi的Nakeuri的answer,簡化我的劇本。

回答

0

這裏是outer apply來幫助你。它被設計用於這種類型的工作:

select c.id as categoryid, 
     o.id as productid, 
     o.date as productdate 
from categories c 
outer apply(select top 1 p.id, p.date 
      from products p 
      where p.categoryid = c.id 
      order by p.date desc) o