2017-07-28 62 views
0

這裏我有一個名爲test2的表。我需要從一個單一的MySQL查詢得到下面的輸出。我嘗試過使用子查詢,但我失敗了。請幫我解決這個問題。如何獲得子查詢中的Mysql COUNT

未決狀態 - 154

完成的狀態 - 159

enter image description here

所需的輸出,我試圖

enter image description here

查詢

SELECT 
    (
     test2.doc_no, 
     SELECT 
      (
       Count(test2.esn) AS pending_quantity, 
       test2.doc_no 
      FROM 
       test2 
      WHERE 
       test2.sttus = 154 
      GROUP BY 
       test2.doc_no 
      ), 
      SELECT 
       (
        Count(test2.esn) AS completed_quantity, 
        test2.doc_no 
       FROM 
        test2 
       WHERE 
        test2.sttus = 159 
       GROUP BY 
        test2.doc_no 
       ) 
    ) 
+0

你可以使用一些組。我可以儘快通過 – Bazaim

+1

'SELECT test2.doc_no,sum(CASE WHEN status = 154 THEN 1 ELSE 0 END)作爲待定,sum(CASE WHEN status = 159 THEN 1 ELSE 0 END) GROUP by doc_no' –

回答

1
SELECT doc_no, 
SUM(STATUS=154) AS pending_quantity, 
SUM(STATUS=159) AS completed_quantity 
FROM 
test2 GROUP BY doc_no 

試試上面的查詢。