假设我有三个表:Customer
,TV
,Radio
Customer
表包含以下属性:customerID
,First name
,Last name
TV
表包含以下属性:customerID
,year
,numTVsBought
Radio
表包含属性,customerID
,year
,numRadiosBought
因此,在电视和广播中,特定的客户ID可以多次出现,对应不同的年份。
现在我想获取一个包含CustomerID,TotalTVsBought,TotalRadiosBought的表
当我这样做时:
SELECT CustomerID, SUM(numTVsBought), SUM(numRadiosBought)
FROM Customer
LEFT JOIN TV on Customer.customerID = TV.customerID LEFT JOIN Radio on Customer.customerID = Radio.customerID
GROUP BY Customer.customerID;
我为numTVsBought获得了正确的值,但是numRadiosBought被夸大了。我是以错误的方式加入表格吗?
答案 0 :(得分:1)
是的,您加入表格的方式是,对于每台电视,您也会添加无线电。 试试这个:
SELECT c.customerId, ifnull(tv_count.counter, 0) as totalTvsBought, ifnull(radio_count.counter,0) as totalRadiosBought
FROM customer c
LEFT OUTER JOIN (
SELECT customerId, SUM(*) as counter
FROM TV
GROUP BY customerId) tv_count
ON tv_count.customerId = c.customerId
LEFT OUTER JOIN (
SELECT customerId, SUM(*) as counter
FROM Radio
GROUP BY customerId) radio_count
ON radio_count.customerId = c.customerId
连接多个表时,您需要像计算机一样思考;在计算之前他会加入所有记录。
答案 1 :(得分:0)
在SQL Server中,我们可以使用公用表表达式(CTE)
来实现它WITH TBL1 AS
(
SELECT C.CustID AS CUST_ID, SUM(T.NoOfTVsBought) AS TOTAL_T From Customer C
LEFT JOIN TVs T
ON C.CustID = T.CustID
GROUP BY C.CustID
)
SELECT CUST_ID, TOTAL_T, TBL2.TOTAL_Radios FROM TBL1
LEFT JOIN(
SELECT C.CustID, SUM(R.NoOfRadBought) AS TOTAL_Radios From Customer C
LEFT JOIN Radios R
ON C.CustID = R.CustID
GROUP BY C.CustID) AS TBL2
ON TBL1.CUST_ID = TBL2.CustID