根据状态分组,然后根据其类别ID统计其产品和总数

Yua*_*hen 0 mysql count select distinct

我有一个包含产品 ID、类别 ID 和产品状态的表格。

+---------+-------------+-------------+
|   id    |   cat_id    |   status    |
+---------+-------------+-------------+
|    1    |     1       |      1      |
|    2    |     1       |      1      |
|    3    |     2       |      1      |
|    4    |     2       |      0      |
|    5    |     1       |      0      |
|    6    |     2       |      0      |
+---------+-------------+-------------+
Run Code Online (Sandbox Code Playgroud)

如何根据其状态进行分组,然后根据其类别 ID 计算其产品和总数?我期待这样:

+---------+-------------+-------------+-----------+
|  cat_id |  published  | unpublished |   totals  |
+---------+-------------+-------------+-----------+
|    1    |     2       |      1      |     3     |
|    2    |     1       |      2      |     3     |
+---------+-------------+-------------+-----------+
Run Code Online (Sandbox Code Playgroud)

哪里status=1publishedstatus=0unpublished

dno*_*eth 6

您需要使用 sum(case) 进行条件聚合:

select cat_id,
   sum(case when status = 1 then 1 else 0 end) as published,  -- only count status 1
   sum(case when status = 0 then 1 else 0 end) as unpublished,-- only count status 0
   count(*) as totals
from tab
group by cat_id
Run Code Online (Sandbox Code Playgroud)

编辑:

我的水晶球显然坏了,但现在已经修好了:-)

如果您只需要计算每个 product_id 一次,您可以使用它:

select cat_id,
   count(distinct case when status = 1 then product_id end) as published,  -- only count status 1
   count(distinct case when status = 0 then product_id end) as unpublished,-- only count status 0
   count(distinct product_id) as totals
from tab join whatever...
group by cat_id
Run Code Online (Sandbox Code Playgroud)