2012-03-09 76 views
1

我的數據庫中有3行(未列出的所有列):添加COUNT(和限定),以SQL語句

**uFirst** | **uApp** 
    Dave  | approved 
    John  | declined 
    Jane  | no 

這個SQL工作,並顯示所有行:

SELECT u.uID, u.uManT, u.uFirst AS 'NomFN', m.uFirst AS 'ManFN', u.uLast AS 'NomLN', m.uLast AS 'ManLN', u.uNomd, u.uApp, u.uApp, u.uAppd, u.uRep, u.uRepd, u.uManT, u.uStatus, u.uManR 
      FROM users AS u LEFT OUTER JOIN users AS m 
      ON u.uManT = m.uID 
      WHERE u.uManR = " . $luID . " 
      AND u.uStatus = 'Physician' 
      ORDER BY u.uLast ASC"; 

當我嘗試添加COUNT,只顯示1行(經批准的):

SELECT COUNT(CASE WHEN u.uApp = 'approved' THEN 1 END) AS Approved, 
     COUNT(CASE WHEN u.uApp = 'declined' THEN 1 END) AS Declined, 
     u.uID, u.uManT, u.uFirst AS 'NomFN', m.uFirst AS 'ManFN', u.uLast AS 'NomLN', m.uLast AS 'ManLN', u.uNomd, u.uApp, u.uApp, u.uAppd, u.uRep, u.uRepd, u.uManT, u.uStatus, u.uManR 
      FROM users AS u LEFT OUTER JOIN users AS m 
      ON u.uManT = m.uID 
      WHERE u.uManR = " . $luID . " 
      AND u.uStatus = 'Physician' 
      ORDER BY u.uLast ASC"; 

我想顯示所有的行,數的計數的用戶被批准。我究竟做錯了什麼?

+0

您的意思是用SUM? – Paulpro 2012-03-09 14:32:36

+0

分享SHOW CREATE TABLE用戶 – rkosegi 2012-03-09 14:33:01

回答

0

在這種情況下,因爲你不使用GROUP BY剛剛返回1行,此查詢應該得到你想要的東西:

SELECT COUNT(uFirst) AS Total, u.uID, u.uManT, 
    u.uFirst AS 'NomFN', m.uFirst AS 'ManFN', u.uLast AS 'NomLN', 
    m.uLast AS 'ManLN', u.uNomd, u.uApp, u.uApp, u.uAppd, u.uRep, 
    u.uRepd, u.uManT, u.uStatus, u.uManR 
FROM users AS u 
LEFT OUTER JOIN users AS m ON u.uManT = m.uID 
WHERE u.uManR = " . $luID . " AND u.uStatus = 'Physician' 
GROUP BY uApp 
ORDER BY u.uLast ASC"; 
+0

此聲明也適用。什麼時候只有1列的分組會比上面的建議好幾個分組呢? – user1041931 2012-03-09 14:46:31

+0

這取決於你想要什麼,基本上計算和分組一個字段就像在這種情況下統計每個uApp的uFirst記錄的數量,由Michael Fredrickson給出的解決方案計算所有記錄,因爲它由所有其他字段進行分組(所以兩者都是有效的解決方案,但結果取決於你的期望) – DarkAjax 2012-03-09 15:00:42

+0

好的,我看到謝謝。但是,仍然存在顯示Approved數量的問題(並且您的解決方案不包括我的CASE:CASE WHEN u.uApp ='approved'THEN 1 END)。當我嘗試檢索'Approved'時,echo $ row ['Approved']; ;,我得到0。 – user1041931 2012-03-09 15:10:44