mysql - 按不存在的值分组

时间:2013-09-05 01:32:19

标签: mysql sql properties group-by

是否可以按不存在分组(对不起,如果这不是正确的术语)。

例如,如果我有一个表格,如:

post_id - 状态

1 - 活跃

2 - 暂停

3 - 举行

状态表的可能值包括:活动,暂停,保持,删除

但状态列在任何给定时间可能有也可能没有所有这些状态类型,但我仍然希望返回一个0计数的状态,即使它不在那里。

是否可以执行诸如(伪查询)之类的操作:

SELECT COUNT(post_id),状态(活动,暂停,保留,删除)FROM FROM GROUP BY状态

P.S。在任何人建议不以这种方式表格之前,我没有选择,因为这就是为这个CMS构建属性表的方式。

2 个答案:

答案 0 :(得分:2)

尝试case声明

SELECT SUM(CASE WHEN status = "active" THEN 1 ELSE 0 END) active_count,
       SUM(CASE WHEN status = "suspended" THEN 1 ELSE 0 END) suspended_count,
       SUM(CASE WHEN status = "hold" THEN 1 ELSE 0 END) hold_count,
       SUM(CASE WHEN status = "deleted" THEN 1 ELSE 0 END) deleted_count
FROM posts;

和这个

SELECT "active", SUM(CASE WHEN status = "active" THEN 1 ELSE 0 END) active_count
FROM posts
UNION
SELECT "suspended", SUM(CASE WHEN status = "suspended" THEN 1 ELSE 0 END) suspended_count
FROM posts
UNION
SELECT "hold", SUM(CASE WHEN status = "hold" THEN 1 ELSE 0 END) hold_count
FROM posts
UNION
SELECT "deleted", SUM(CASE WHEN status = "deleted" THEN 1 ELSE 0 END) deleted_count
FROM posts

更好

SELECT "active", COUNT(*) active_count
FROM posts WHERE status = "active"
UNION
SELECT "suspended", COUNT(*) suspended_count
FROM posts WHERE status = "suspended"
UNION
SELECT "hold", COUNT(*) hold_count
FROM posts WHERE status = "hold"
UNION
SELECT "deleted", COUNT(*) deleted_count
FROM posts WHERE status = "deleted"

请参阅SQL小提琴here

答案 1 :(得分:0)

我的查询是相同的,但在Oracle中。接下来进行工作。

table3.col2

积分:Using pivot on multiple columns of an Oracle row