Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

sql server - SQL JOIN 3 TABLES WITH COUNT AND GROUP BY CLAUSE

I Have 3 tables like that:

EXPEDITION (ID, CreateDate, Status);
PACKAGE (ID, EXPEDITION_ID)
ITEM (ID, EXPEDIITONPACKAGE_ID);

I need to know, for each expedition, the quantity of packages and the quantity of items.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATE

This is the query that seems to have it.

    SELECT 
        E.ID, 
        P.Packages, 
        I.Items 
    FROM EXPEDITION E

    LEFT JOIN (
        SELECT DISTINCT E.ID, COUNT(P.ID) AS "Packages" FROM EXPEDITION E
        LEFT JOIN PACKAGE P
        ON E.ID = P.EXPEDITION_ID
        GROUP BY E.ID
    ) P
    ON E.ID = P.ID

    LEFT JOIN (
        SELECT DISTINCT P.ID as "PackageID", COUNT(I.ID) AS "Items" FROM PACKAGE P
        JOIN ITEM I
        ON P.ID = I.EXPEDIITONPACKAGE_ID
        GROUP BY P.ID
    ) I
    ON P.ID = I.PackageId

    GROUP BY 
        E.ID, 
        P.Packages, 
        I.Items

    ORDER BY 
        E.ID

It has two inner queries, that count the IDs separately, and they are joined in the main query to show the results.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...