MySQL 联合所有列

标签 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

我在查询中到底遗漏了什么。任何帮助将不胜感激。

最佳答案

通过使用 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代替内部连接 作为下一个:-

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/

相关文章:

sql - 为什么这些是字符串末尾的问号

mysql - 如何防止此 JOIN 查询进行几乎全表扫描

MySQL JOIN 具有相应 ID 的多个列

c# - 如何在 LINQ 的表达式树中创建连接?

php - 如何从动态添加唯一字段的表单中将数据存储在 mysql 数据库中?

mysql - 意外 $'\r' : command not found after mysql query in shell

mysql - 指向 MySQL 查询抽象接口(interface)的指针片段

mysql - 如何从期望脚本中的转储文件加载 MySQL DB

sql - Postgres 条件选择?

java - 如何将列表中的每个字段数据存储在字符串中?