0

如何将下面的两个 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
4

2 回答 2

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
于 2012-11-21T20:18:06.470 回答
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
于 2012-11-21T20:20:12.690 回答