2013-07-28 64 views
0

編輯:我改變了表格。請參閱更新的表:組合字段時獲得計數

在我的示例表

post   status  
------------- ------------- 
post1   delivered 
post2   undelivered 
post3   delayed 
post4   delivered 
post5   undelivered 

是否有可能得到的delivered數量和組合在單個查詢undelivered + delayed多少?

像這樣:

post   status  
------------- ------------- 
delivered  2 
undelivered  3 
+1

如果你在1排中得到結果,你關心嗎?或2行是好嗎?如果是2,那麼您可以在2個查詢之間使用UNION。這有幫助嗎? – Artem

+0

你想要的輸出是什麼? –

回答

2
SELECT 
    SUM(IF(status = 'delivered', 1, 0)) as `delivered_count`, 
    COUNT(postid) as `all_count` 
FROM 
    table 

應該正常工作。這說明有僅是deliveredundelivered狀態 - 如果有更多的,但你還是隻想計算這兩個,你可以做到以下幾點:

SELECT 
    SUM(IF(status = 'delivered', 1, 0)) as `delivered_count`, 
    SUM(IF(status = 'delivered' OR status = 'undelivered', 1, 0)) as `all_count` 
FROM 
    table 

如果你想deliveredundelivered計數分別,你可以使用GROUP BY

SELECT 
    COUNT(postid), 
    status 
FROM 
    table 
WHERE 
    status IN ('delivered', 'undelivered') 
GROUP BY 
    status 
0
SELECT COUNT(*) 
FROM table 
GROUP BY status = 'delivered' 
ORDER BY status = 'delivered' DESC 

這將導致

count of delivered 
count of everything else 
0

假設deliveredundelivereddelayed是唯一可用的狀態,

SELECT SUM(CASE WHEN status = 'delivered' THEN 1 END) `delivered`, 
     SUM(CASE WHEN status <> 'delivered' THEN 1 END) `delayed + undelivered` 
FROM tableName 

輸出

╔═══════════╦═══════════════════════╗ 
║ DELIVERED ║ DELAYED + UNDELIVERED ║ 
╠═══════════╬═══════════════════════╣ 
║   2 ║      3 ║ 
╚═══════════╩═══════════════════════╝ 

根據您的修改,你希望它有多行,

SELECT CASE WHEN status = 'delivered' THEN 'delivered' 
        ELSE 'undelivered' 
     END post, 
     COUNT(*) totalCount 
FROM tableName 
GROUP BY CASE WHEN status = 'delivered' THEN 'delivered' 
        ELSE 'undelivered' 
      END 

輸出

╔═════════════╦════════════╗ 
║ POST  ║ TOTALCOUNT ║ 
╠═════════════╬════════════╣ 
║ delivered ║   2 ║ 
║ undelivered ║   3 ║ 
╚═════════════╩════════════╝ 
+0

我的表格還有一個'DATETIME'字段,雖然這裏沒有顯示。使用您的查詢,是否可以顯示按月份分組的每個和? – enchance

+0

是的。您希望我通過將它們按月分組來修改哪個查詢? –

+0

您寫的第一個查詢。 – enchance

0

如果你只有三個狀態,並且要一排與交付的項目數,以及一個列有未交付+延遲的項目數,您可以使用此查詢:

SELECT 
    CASE WHEN status = 'delivered' THEN status 
     ELSE 'undelivered+delayed' END status, 
    COUNT(*) cnt 
FROM 
    yourtable 
GROUP BY 
    CASE WHEN status = 'delivered' THEN status 
     ELSE 'undelivered+delayed' END