2015-02-23 79 views
-2

我需要使用子查詢將兩個查詢語句連接在一起的幫助。我很困惑我如何將兩者結合在一起。我很感激幫助。SQL的子查詢

SELECT * FROM MEDICAL_PROCEDURE 
JOIN PROCEDURE_CATEGORY ON medical_procedure.procedure_category_id = PROCEDURE_CATEGORY.PROCEDURE_CATEGORY_ID; 

SELECT 
     Medical_procedure.medical_procedure_id, 
     COUNT(procedure_tool_supply.medical_procedure_id) AS Supply_Needed 
FROM Procedure_tool_supply 
JOIN Medical_Procedure on Procedure_tool_supply.medical_procedure_id = Medical_procedure.medical_procedure_id 
GROUP BY Procedure_tool_supply.medical_procedure_id 
HAVING COUNT(Procedure_tool_supply.medical_procedure_id) < 3; 
+0

可以請你分享烏爾表結構? ñ詳細說明你想要結果? – 2015-02-23 03:51:45

+0

這是用於mysql還是sql-server?這是兩個非常不同的數據庫引擎。 – 2015-02-23 04:35:32

回答

0

不能真正測試沒有測試數據,但這應該工作。希望我正確地找出你想要做的事情:

SELECT * 
FROM 
    MEDICAL_PROCEDURE P 
    JOIN PROCEDURE_CATEGORY C ON 
    P.procedure_category_id = C.PROCEDURE_CATEGORY_ID 
    cross apply (
    SELECT 
     COUNT(T.medical_procedure_id) AS Supply_Needed 
    FROM 
     Procedure_tool_supply T 
    where 
     T.medical_procedure_id = P.medical_procedure_id 
    GROUP BY 
     T.medical_procedure_id 
    HAVING 
     COUNT(T.medical_procedure_id) < 3 
) T 
0

目前尚不清楚你試圖達到的目標。但如果您的意圖是在第一個查詢的每一行中包含來自第二個查詢的第二個查詢的派生的Supply_Needed列,並限制返回到第二個查詢返回的值爲medical_procedure_id的那些行,那麼...

你可以做這樣的事情:

SELECT mp.* 
    , pc.* 
    , ct.Supply_Needed 
    FROM MEDICAL_PROCEDURE mp 
    JOIN PROCEDURE_CATEGORY pc 
    ON mp.procedure_category_id = pc.PROCEDURE_CATEGORY_ID 
    JOIN (SELECT pr.medical_procedure_id 
       , COUNT(ts.medical_procedure_id) AS Supply_Needed 
      FROM Procedure_tool_supply ts 
      JOIN Medical_Procedure pr 
      ON ts.medical_procedure_id = pr.medical_procedure_id 
      GROUP BY ts.medical_procedure_id 
     HAVING COUNT(ts.medical_procedure_id) < 3 
     ) ct 
    ON ct.medical_procedure_id = mp.medical_procedure_id