gpt4 book ai didi

mysql - 比较两年内的日期

转载 作者:行者123 更新时间:2023-11-29 21:07:58 25 4
gpt4 key购买 nike

我有一个人口表,我想比较两年内的人口。

我的表结构:
id(自动递增),类型(男人,女人, child ),人口(1到10000),日期

我想在查询下运行两个并显示到一个表结果中:

查询1:

SELECT type,count(population) as count_of_year1
FROM population
where date between '2013-01-01' and '2013-01-24'
GROUP BY type

查询2:

SELECT type, count(population) as count_of_year2
FROM population
where date between '2014-01-01' and '2014-01-24'
GROUP BY type

我需要这个结果:

|类型 | 2013年人口| 2014年人口

如何做到这一点?

最佳答案

使用case表达式进行条件计数:

SELECT type,
count(case when date between '2013-01-01' and '2013-01-24' then population end) as count_of_year1,
count(case when date between '2014-01-01' and '2014-01-24' then population end) as count_of_year2
FROM population
GROUP BY type

添加此 where 子句以加快速度(如果需要):

where date between '2013-01-01' and '2013-01-24'
or date between '2014-01-01' and '2014-01-24'

关于mysql - 比较两年内的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36649336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com