加入这些CTE的方式是什么?

时间:2019-04-24 21:37:22

标签: sql sql-server sql-server-2005

在使用以下SQL代码时,我似乎找不到合适的方法来正确连接正在创建的2个CTE,以获取正确的(或至少是我期望的)记录数量。

TEST 1&TEST 2仅返回每个CTE独立产生的记录; n m

我希望可以使用TEST 3(一个左联接)或TEST 4(一个内联接)来检索 n 记录,但是我使用哪种类型的联接(并且我尝试了所有等联接);我不断收到 m 条记录。


WITH
CTE_ALL_INSPECTIONS AS
(
    SELECT
            InspectorId,
            InspectionetailId
            ...
        FROM ...
        WHERE ...
),

CTE_ALL_INSPECTORS AS
(
    SELECT DISTINCT
            InspectorId,
            COUNT(InspectionDetailId) Inspections
        FROM CTE_ALL_INSPECTIONS
        GROUP BY InspectorId
)

/*
TEST 1:
*/
/*
    SELECT * FROM CTE_ALL_INSPECTORS
*/

/*
TEST 2:
*/
/*
    SELECT * FROM CTE_ALL_INSPECTIONS
*/

/*
TEST 3:
*/
/*
    SELECT
            CTE_ALL_INSPECTIONS.*,
            CTE_ALL_INSPECTORS.Inspections
        FROM
            CTE_ALL_INSPECTORS
            LEFT JOIN CTE_ALL_INSPECTIONS
                ON CTE_ALL_INSPECTIONS.InspectorId = CTE_ALL_INSPECTORS.InspectorId
*/

/*
TEST 4:
*/
/*
    SELECT
            CTE_ALL_INSPECTIONS.*,
            CTE_ALL_INSPECTORS.Inspections
        FROM
            CTE_ALL_INSPECTORS
            INNER JOIN CTE_ALL_INSPECTIONS
                ON CTE_ALL_INSPECTIONS.InspectorId = CTE_ALL_INSPECTORS.InspectorId
*/

如何获取所需的记录?或我还能如何加入这些表格?

1 个答案:

答案 0 :(得分:1)

使用您的TEST 3,但将... Inspections作为最左边的查询:

SELECT CTE_ALL_INSPECTIONS.*
    , CTE_ALL_INSPECTORS.Inspections 
FROM CTE_ALL_INSPECTIONS
    LEFT JOIN CTE_ALL_INSPECTORS
        ON CTE_ALL_INSPECTIONS.InspectorId = CTE_ALL_INSPECTORS.InspectorId

这是说:“将所有检查以及所有来自检查员的计数都给我。”