左[外部]不带交集即可计数

时间:2019-09-17 21:40:54

标签: tsql

我有以下模式

enter image description here

我想让所有汽车以及每辆汽车的number of models和每辆汽车的number of remaining colors
我可以得到number of models,但每辆车都不能得到number of remaining colors。我知道我必须做没有交叉的左[外部]连接。但它不起作用

我可能也有没有任何颜色的型号。在这种情况下,ModelColors表中将没有任何条目

select 
    c.CarID,
    c.CarName,
    T1.[Num Of Models],
    T2.[Remaining Colors]
from Cars c
LEFT JOIN 
    (
        SELECT m.CarID, COUNT(1) AS 'Num Of Models' 
        FROM Models m
        GROUP BY m.CarID
    ) AS T1 ON T1.CarID = c.CarID
LEFT JOIN 
    (
        SELECT m1.CarID, COUNT(1) AS 'Remaining Colors' 
        FROM Colors col
        LEFT JOIN ModelColors mc on mc.ColorID = col.ColorID
        LEFT JOIN Models m1 on m1.ModelID = mc.ModelID
        WHERE mc.ColorID IS NULL
        GROUP BY m1.CarID
    ) AS T2 ON T2.CarID = c.CarID

1 个答案:

答案 0 :(得分:0)

第二个派生表(from/join)中的T2子句是错误的。
您应仅使用ModelsModelColors

SELECT m1.CarID, COUNT(1) AS 'Remaining Colors' 
FROM Models m
LEFT JOIN ModelColors mc
    ON m.ModelID = mc.ModelID

整个查询应如下所示:

SELECT 
    c.CarID,
    c.CarName,
    T1.[Num Of Models],
    T2.[Remaining Colors]
FROM Cars c
LEFT JOIN 
    (
        SELECT m.CarID, COUNT(1) AS 'Num Of Models' 
        FROM Models m
        GROUP BY m.CarID
    ) AS T1 ON T1.CarID = c.CarID
LEFT JOIN 
    (
        SELECT m1.CarID, COUNT(1) AS 'Remaining Colors' 
        FROM Models m
        LEFT JOIN ModelColors mc
            ON m.ModelID = mc.ModelID
    ) AS T2 ON T2.CarID = c.CarID

由于您只想计算颜色,因此此查询完全不需要颜色表。