我有类别和产品表。我希望根据类别在一行中获得具有最大日期的产品记录。如果根本没有产品,我至少要显示该类别。产品的ID将为NULL,因为没有记录,ProductDate也将为NULL。
我尝试过这个脚本并且我没有得到任何东西(我没有把这个类别的产品作为@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
如何才能让一条记录与产品类别相匹配('因为我没有该类别的任何产品)?
e.g。
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
更新
我发现了错误,因为我没有完全发布问题。我正在做另外的
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 :(得分: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