我有一个用于案例的 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
我在查询中到底遗漏了什么。任何帮助将不胜感激。
最佳答案
通过使用 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
代替内部连接
作为下一个:-
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
关于MySQL 联合所有列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41259674/