我对SQL Server比较陌生,所以如果我错过了一些明显的东西,请耐心等待。
我有一个包含表格Retailers
,Wholesalers
和RetailerWholesaler
的数据库。
目前,每个零售商都可以拥有零个,一个或两个批发商(当然,这可能会在不知不觉中发生变化!)。我在创建包含RetailerID,PrimaryWholesalerID和SecondaryWholesalerID列的视图时遇到问题。无论我尝试过什么,我都会在不同的行上继续使用Primary / Secondary:
RetailerID | PrimaryWholesalerID | SecondaryWholesalerID
-----------+---------------------+----------------------
100 | 8888 | NULL
100 | NULL | 9999
我想要达到的目的是:
RetailerID | PrimaryWholesalerID | SecondaryWholesalerID
-----------+---------------------+----------------------
100 | 8888 | 9999
这是我目前的剧本:
SELECT
r.RetailerID,
CASE WHEN rw.RetailerWholesalerType = 'Primary'
THEN w.WholesalerID END PrimaryWholesalerID
CASE WHEN rw.RetailerWholesalerType = 'Secondary'
THEN w.WholesalerID END SecondaryWholesalerID
FROM
Retailers r
LEFT OUTER JOIN
RetailerWholesaler rw ON r.RetailerID = rw.RetailerID
LEFT OUTER JOIN
Wholesalers w ON rw.WholesalerID = w.WholesalerID
即使没有主要或辅助批发商,我仍然希望显示RetailerID
。
我正在使用SQL Server 2017.提前感谢您的任何帮助或见解。
答案 0 :(得分:3)
您可以使用MAX()
SELECT r.RetailerID,
MAX(CASE WHEN rw.RetailerWholesalerType = 'Primary'
THEN w.WholesalerID END) PrimaryWholesalerID
MAX(CASE WHEN rw.RetailerWholesalerType = 'Secondary'
THEN w.WholesalerID END) SecondaryWholesalerID
FROM Retailers r
LEFT OUTER JOIN RetailerWholesaler rw
ON r.RetailerID = rw.RetailerID
LEFT OUTER JOIN Wholesalers w
ON rw.WholesalerID = w.WholesalerID
GROUP BY r.RetailerID
答案 1 :(得分:2)
我建议使用聚合来写这个:
SELECT r.RetailerID,
MAX(CASE WHEN rw.RetailerWholesalerType = 'Primary'
THEN w.WholesalerID
END) as PrimaryWholesalerID
MAX(CASE WHEN rw.RetailerWholesalerType = 'Secondary'
THEN w.WholesalerID
END) as SecondaryWholesalerID
FROM Retailers r LEFT OUTER JOIN
RetailerWholesaler rw
ON r.RetailerID = rw.RetailerID LEFT OUTER JOIN
Wholesalers w
ON rw.WholesalerID = w.WholesalerID
GROUP BY r.RetailerID;