问题描述
- 求一个Mysql语句 查询出当前周的数据按照天分组
- SELECT
DATE_FORMAT(uploadTime_beg%Y-%m-%d"") as time
SUM(field01) as sumStatus1
SUM(field02) as sumStatus2
SUM(field03) as sumStatus3
SUM(field04) as sumStatus4
SUM(field05) as sumStatus5
FROM
health_realdata
WHERE DATE_FORMAT(uploadTime_beg'%Y%u') = DATE_FORMAT(CURDATE()'%Y%u')
GROUP BY DATE_FORMAT(uploadTime_beg%Y-%m-%d"");这个SQL查出的数据如下: ![图片说明](http://img.ask.csdn.net/upload/201511/24/1448359276_377950.png) 我想要的效果是:虽然数据库中没有2015-11-25的数据,但是也要查出来,只是后面的值显示为0. 请问在MYSQL中如何实现,上面的SQL如何修改呢。 我看到网上说需要一个日历辅助表,说的不是很详细,我试了一下好像有问题,如果这种方法可行,还请大牛们写详细点,谢谢。
解决方案
思路:
1、将你上边查询出来的结果跟你说的那个有从2015-11-01 到2015-11-30的日历辅助表进行右连接查询
2、将1中查询出的结果进行再次的查询处理,将null值更换为0;
下边的为代码示意,没有进行调试,应该会有问题,大体结构是这样的:
SELECT o.time case when o.sumStatus1 is null then 0 else o.sumStatus1 end as sumStatus1 case when o.sumStatus2 is null then 0 else o.sumStatus2 end as sumStatus2 case when o.sumStatus3 is null then 0 else o.sumStatus3 end as sumStatus3 case when o.sumStatus4 is null then 0 else o.sumStatus4 end as sumStatus4 case when o.sumStatus5 is null then 0 else o.sumStatus5 end as sumStatus5 ( ( SELECT DATE_FORMAT(uploadTime_beg%Y-%m-%d"") as time SUM(field01) as sumStatus1 SUM(field02) as sumStatus2 SUM(field03) as sumStatus3 SUM(field04) as sumStatus4 SUM(field05) as sumStatus5 FROM health_realdata WHERE DATE_FORMAT(uploadTime_beg'%Y%u') = DATE_FORMAT(CURDATE()'%Y%u') GROUP BY DATE_FORMAT(uploadTime_beg%Y-%m-%d""); ) as a right join 表d on a.time = d.time ) o
解决方案三:
select * from Table
where date_colum > date_add(now()interval - dayofweek(now())+1 day)
and date_colum < date_add(now()interval - dayofweek(now())+7 day)
group by day(date_colum)
打赏吧。。
解决方案四:
@晓呆同学 ,多谢,这里用右链接才是王道,我昨天用的事左连接不对,后来改成右链接位置放的不对,导致还是出不来。
你的思路是对的,谢谢。
不过我没有分,不然都给你。
时间: 2024-10-02 05:09:44