sql语句查询本周每天的数据量,如果没有该天,数据量默认为0;

我的sql语句

SELECT 
   WEEKDAY(osr.created_date) AS weekDay, 
   IF (count(1) IS NULL, 0, count(1)) AS num 
FROM osr_work AS osr
INNER JOIN el_user AS el  ON el.id = 141
WHERE 
    osr.teacher_id = 141 AND 
    YEARWEEK(date_format(osr.created_date,'%Y-%m-%d')) = YEARWEEK(now()) 
GROUP BY WEEKDAY(osr.created_date);

结果:图片描述

0-6:分别代表周一至周日
我希望得到周一至周日所有的数据,因为周一和周五,周六,周日没有数据,就默认num为0;我该如何写,求指导!!!

阅读 8.8k
5 个回答
select day, max(num)
from (
    SELECT 
       WEEKDAY(osr.created_date) AS day, 
       IF (count(1) IS NULL, 0, count(1)) AS num 
    FROM osr_work AS osr
    INNER JOIN el_user AS el  ON el.id = 141
    WHERE 
        osr.teacher_id = 141 AND 
        YEARWEEK(date_format(osr.created_date,'%Y-%m-%d')) = YEARWEEK(now()) 
    GROUP BY WEEKDAY(osr.created_date)
    UNION
    SELECT * from (
        select 0 day, 0 num
        UNION
        select 1, 0  
        UNION
        select 2, 0  
        UNION
        select 3, 0  
        UNION
        select 4, 0  
        UNION
        select 5, 0
        UNION
        select 6, 0  
    ) b
) c 
group by day

改用LEFT JOIN就行了呀。

建议建一张辅佐表 weekDay 0-6,num 全部为0, left join辅佐表就可以了。

日期left join 你要查询的条件,然后在从这个获取的数据集中查询数据,然后判断num是不是null就行了

SELECT
    osr_weekday.weekDay,
    count(1) AS num
FROM
    osr_work osr,osr_weekday
WHERE
    WEEKDAY(osr.created_date) = osr_weekday.weekDay AND
    osr.teacher_id = 141 AND 
    YEARWEEK(date_format(osr.created_date,'%Y-%m-%d')) = YEARWEEK(now())
GROUP BY osr_weekday.weekDay


union ALL

SELECT 
    osr_weekday.weekDay ,
    0 
FROM 
    osr_weekday 
WHERE 
    osr_weekday.weekDay not in (
        SELECT 
            osr_weekday.weekDay
        FROM 
            osr_work osr,
            osr_weekday
        WHERE
            WEEKDAY(osr.created_date) = osr_weekday.weekDay AND
            osr.teacher_id = 141 AND 
            YEARWEEK(date_format(osr.created_date,'%Y-%m-%d')) = YEARWEEK(now())
        GROUP BY osr_weekday.weekDay
 )
ORDER BY weekDay

想把not in优化,折腾了半天还是老样子~有带飞的吗

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题