如何将下面的两个mysql查询合并到一个查询中?
SELECT R12NC, COUNT(*) AS `count1` FROM alink where Option_a = 1 GROUP BY R12NC
SELECT R12NC, COUNT(*) AS `count2` FROM alink where Option_x = 1 GROUP BY R12NC
答案 0 :(得分:0)
使用嵌套在聚合函数中的case
语句:
SELECT R12NC,
sum(case when Option_a = 1 then 1 else 0 end) as `count1`,
sum(case when Option_x = 1 then 1 else 0 end) as `count2`
FROM alink
GROUP BY R12NC
答案 1 :(得分:0)
两种方式。如果只需要两列,请使用UNION
SELECT R12NC, COUNT(*) AS `count1` FROM alink where Option_a = 1 GROUP BY R12NC
UNION
SELECT R12NC, COUNT(*) AS `count2` FROM alink where Option_x = 1 GROUP BY R12NC
如果你想要3列,那么就像:
SELECT R12NC, SUM(CASE WHEN Option_a = 1 THEN 1 ELSE 0 END) as `count1`,
SUM(CASE WHEN Option_x = 1 THEN 1 ELSE 0 END) as `count2`
FROM alink
GROUP BY R12NC