mysql - 比较两年内的日期

标签 mysql sql date

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

我的表结构:
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/

相关文章:

mysql - 如何根据多行中的最大值选择单行

mysql - 无法以新创建的 MySQL 用户身份登录

sql - 我应该如何在 (My)SQL 中实现一对一关系?

c - 如何检查字符串日期是否已经过了某个日期

sql - 如何为 DateDiff 动态传入 date_or_time_part?

java - java.util.GregorianCalendar 在 1976 年 3 月 28 日到 3 月 29 日之间发生了什么?

php - 如何在 php 中设置输出命令的样式

php - 未定义的属性:我的代码中的 stdClass::$account_id 错误

mysql - 使用 JOIN 过滤数据

mysql - 如何在 ssp 简单类中使用 UNION ALL?