[英]Mysql:Combine select queries from same table
我想将不同的查询组合成一个字段并按字段分组。 当我分别执行查询时,我得到了所需的结果,但我无法将它们合并。我认为union或union all应该合并它们。
下面是查询。
(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 |
+------------+--------+
一切都一样。 第二个结果不存在。
您需要像这样的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.