这是我开始的表
CMS | defect_status
________________________
1 | true
2 | false
3 | true
3 | false
这就是我想要的东西
CMS | true_defects | false_defects
1 | 1 | 0
2 | 0 | 1
3 | 1 | 1
所以这是我的代码
SELECT DISTINCT
false_table.CMS,
true_table.true_defects,
false_table.false_defects
FROM(
SELECT DISTINCT
CMS,
COUNT(*) AS true_defects
FROM data_table
WHERE defect_status = 'true'
GROUP BY CMS
) as true_table
FULL JOIN(
SELECT DISTINCT
CMS,
COUNT(*) AS false_defects
FROM data_table
WHERE defect_status = 'false'
GROUP BY CMS
) as false_table
ON true_table.CMS = false_table.CMS
我想选择所有CMS,“false_table”和“true_table”。 如果我选择“false_table.CMS”(如上面的代码所示),这就是我得到的:
CMS | true_defects | false_defects
2 | 0 | 1
3 | 1 | 1
CMS“1”已经消失,因为它不在false_table.CMS列中
谢谢
答案 0 :(得分:1)
您可以通过以下简单的case
和group by
来实现它:
SELECT t1.CMS
,sum(CASE defect_status
WHEN true
THEN 1
ELSE 0
END) AS true_status
,sum(CASE defect_status
WHEN false
THEN 1
ELSE 0
END) AS false_status
FROM Table1 AS t1
GROUP BY CMS