Mysql:组合同一个表中的选择查询

时间:2018-01-30 08:25:52

标签: mysql sql node.js

我想将不同的查询组合成一个按字段分组。当我分开执行查询时,我得到了所需的结果,但我无法将它们组合起来。我认为联合或联合都应该将它们结合起来。

以下是查询。

(select cmb_region, count(*) as count1 
 from leases 
 where txt_contr_end <= CURDATE() 
 group by cmb_region) 
union 
(select cmb_region, count(*) as count2 
 from leases 
 where txt_contr_end >= CURDATE() 
 group by cmb_region);

这是我得到的结果:

+------------+--------+
| cmb_region | count1 |
+------------+--------+
| Central    |    648 |
| NGA        |    647 |
| NULL       |    140 |
| SGS        |      1 |
| Central    |    855 |
| NGA        |    855 |
| NULL       |      5 |
+------------+--------+

一切都是一样的名字。计数二的结果不存在。

1 个答案:

答案 0 :(得分:0)

你需要2个不同的列。

(select cmb_region, count(*) as count1, 0 as count2 
 from leases 
 where txt_contr_end <= CURDATE() 
 group by cmb_region) 
union 
(select cmb_region, 0 as count1, count(*) as count2 
 from leases 
 where txt_contr_end >= CURDATE() 
 group by cmb_region);

如果您需要在同一行中<或者

 select cmb_region, 
        sum(CASE WHEN txt_contr_end <= CURDATE() THEN 1 ELSE 0 END) as count1,
        sum(CASE WHEN txt_contr_end >= CURDATE() THEN 1 ELSE 0 END) as count2 
 from leases 
 group by cmb_region