0

编辑:我改变了桌子。请参阅更新表:

在我的示例表中

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

是否可以在单个查询中获得组合delivered的数量和undelivered+数量?delayed

像这样:

post            status      
-------------   -------------
delivered       2
undelivered     3
4

4 回答 4

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
于 2013-07-28T18:51:00.903 回答
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 ║
╚═════════════╩════════════╝
于 2013-07-28T18:51:20.817 回答
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
于 2013-07-28T18:51:26.730 回答
0
SELECT COUNT(*)
FROM table
GROUP BY status = 'delivered'
ORDER BY status = 'delivered' DESC

这将导致

count of delivered
count of everything else
于 2013-07-28T18:50:25.810 回答