MySQL联盟所有列

时间:2016-12-21 09:46:57

标签: mysql sql join union

我有一个案例的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

它给我的结果为Fiddler result

但我想要结果为 enter image description here

我在查询中究竟缺少什么。任何帮助将不胜感激。

3 个答案:

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

<强>更新: -

对于只有一条记录的产品,其状态仅CLOSEDOPEN使用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