我有一个案例的mysql表。它有每个产品的产品名称,可以有多个具有不同状态的记录。
MySQL Fiddler:SQL Fiddler Link
SELECT
product , count(*) as totalopen
FROM cases
where status='OPEN'
group by product
union all
SELECT
product , count(*) as totalclosed
FROM cases
where status='CLOSED'
group by product
我在查询中究竟缺少什么。任何帮助将不胜感激。
答案 0 :(得分:2)
使用Inner Join
:
Select a.product, totalopen , totalclosed
from (
SELECT
product , count(*) as totalopen
FROM cases
where status='OPEN'
group by product ) a
inner join (
SELECT
product ,count(*) as totalclosed
FROM cases
where status='CLOSED'
group by product ) b
on a.product = b.product.
<强>更新: - 强>
对于只有一条记录的产品,其状态仅CLOSED
或OPEN
使用Full Outer Join
代替inner join
作为下一个: -
Select isnull(a.product,b.product) product, isnull(totalopen,0) totalopen , isnull(totalclosed,0) totalclosed
from (
SELECT
product , count(*) as totalopen
FROM cases
where status='OPEN'
group by product ) a
full outer join (
SELECT
product ,count(*) as totalclosed
FROM cases
where status='CLOSED'
group by product ) b
on a.product = b.product
答案 1 :(得分:1)
将mock().actualCall("HAL_AS393x_GetData");
return mock().XXXReturnValue();`
表达式用于条件聚合:
case
如果您想要包含仅具有其他状态(例如待处理状态)的商品,请删除SELECT product,
count(case when status='OPEN' then 1 end) as totalopen,
count(case when status='CLOSED' then 1 end) as totalclosed
FROM cases
where status in ('OPEN', 'CLOSED')
group by product
条款。
答案 2 :(得分:0)
使用case
表达式并计算相关的表达式。
SELECT
product ,
count(case when status = 'OPEN' then 1 end) as totalopen,
count(case when status = 'CLOSED' then 1 end) as totalclosed
FROM cases
group by product;
它使用
这一事实COUNT(1) = 1
COUNT(NULL) = 0
和
case when 1 = 1 then 1 end -- return 1
case when 1 = 2 then 1 end -- return null