在组合字段时获取计数

时间:2013-07-28 18:39:32

标签: mysql

编辑:我改变了表格。请参阅更新的表格:

在我的示例表中

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

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

像这样:

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

4 个答案:

答案 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

答案 1 :(得分:0)

SELECT COUNT(*)
FROM table
GROUP BY status = 'delivered'
ORDER BY status = 'delivered' DESC

这将导致

count of delivered
count of everything else

答案 2 :(得分: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 ║
╚═════════════╩════════════╝

答案 3 :(得分: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