2

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

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

post_id - 状态

1 - 活跃

2 - 暂停

3 - 保持

状态表的可能值有:active、suspended、hold、deleted

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

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

SELECT COUNT(post_id), status(active,suspended,hold,deleted) FROM users GROUP BY status

Ps 在有人建议不要以这种方式制作表格之前,我别无选择,因为这是该 CMS 的属性表的结构方式。

4

2 回答 2

4

尝试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 小提琴

于 2013-09-05T02:33:44.070 回答
0

我的查询是相同的,但在 Oracle 中。下面做作业。

select * from (
  select status from users
)
pivot (
  count(status) as count
  for status in ('active' as A, 'suspended' as S, 'hold' as H, 'deleted' as D)
);

学分:在 Oracle 行的多个列上使用数据透视

于 2019-08-27T08:01:42.697 回答