sql查询一年里1到4月的数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql查询一年里1到4月的数据相关的知识,希望对你有一定的参考价值。
Temp
year month amount
1991 1月 1.1
1991 2 月 1.2
1991 3 月 1.3
1991 4 月 1.4
1992 1 月 2.1
1992 2 月 2.2
1992 3 月 2.3
1992 4 月 2.4
查成这样一个结果
year 1月 2月 3月 4月
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4
求解
不对,这样查询和原来一模一样,请看清楚需要实现效果
追答select year,
(select amount from temp t1 where t1.year=t2.year and t1.month='1月') 1月,
(select amount from temp t1 where t1.year=t2.year and t1.month='2月') 2月,
(select amount from temp t1 where t1.year=t2.year and t1.month='3月') 3月,
(select amount from temp t1 where t1.year=t2.year and t1.month='4月') 4月
from temp t2 group by year;
mysql 根据某一年 查询12个月的数据
1、时间字段是datetime类型
2、需要用到中间表,表结构和数据链接下载
https://pan.baidu.com/s/1sAQ78e3Ao-KwvYJlaipbKQ
3、前两个 adddate 月日需要在数据库写死 从每年的-01-01开始,-最后一个日期同理xxxx-12-31
4、下面是sql
select concat(month(years.date),‘月‘) as year, years.date, date_format(years.date, ‘%Y-%m‘) AS years, sum( case when bri.status = ‘1‘ then 1 else 0 end ) as num, -- 总数 sum( case when bri.status = ‘1‘ and bri.sex=‘1‘ then 1 else 0 end ) as numman, -- 男性数量 sum( case when bri.status = ‘1‘ and bri.sex=‘2‘ then 1 else 0 end ) as numgrid -- 女性数量 from ( select adddate(‘2018-01-01‘, INTERVAL numlist.id month) as ‘date‘, numlist.id from ( select n100.i * 1 as id from num as n100 ) as numlist where adddate(‘2018-01-01‘, INTERVAL numlist.id month) <= ‘2018-12-31‘ ) years left join building_resident_info bri on date_format(years.date, ‘%Y-%m‘) = date_format(bri.entrytime, ‘%Y-%m‘) and bri.status=‘1‘ and bri. status = ‘1‘ and bri.orgid like concat(‘37.02.82‘, ‘%‘) group by years.date
5、效果图如下
附带:
1、还有一种写法,是把12个月写死的
sql:
select case month(bri.entrytime) when ‘1‘ then sum(bri.status) else 0 end as 1月, case month(bri.entrytime) when ‘2‘ then sum(bri.status) else 0 end as 2月, case month(bri.entrytime) when ‘3‘ then sum(bri.status) else 0 end as 3月, case month(bri.entrytime) when ‘4‘ then sum(bri.status) else 0 end as 4月, case month(bri.entrytime) when ‘5‘ then sum(bri.status) else 0 end as 5月, case month(bri.entrytime) when ‘6‘ then sum(bri.status) else 0 end as 6月, case month(bri.entrytime) when ‘7‘ then sum(bri.status) else 0 end as 7月, case month(bri.entrytime) when ‘8‘ then sum(bri.status) else 0 end as 8月, case month(bri.entrytime) when ‘9‘ then sum(bri.status) else 0 end as 9月, case month(bri.entrytime) when ‘10‘ then sum(bri.status) else 0 end as 10月, case month(bri.entrytime) when ‘11‘ then sum(bri.status) else 0 end as 11月, case month(bri.entrytime) when ‘12‘ then sum(bri.status) else 0 end as 12月 from building_resident_info bri where date_format(bri.entrytime, ‘%Y‘) = ‘2018‘ and bri.orgid like concat(‘37.02.82.01‘, ‘%‘) and bri.status=‘1‘
效果:
如有疏漏,请指正!谢谢。
以上是关于sql查询一年里1到4月的数据的主要内容,如果未能解决你的问题,请参考以下文章