每周一个月的分组日期

时间:2019-10-10 05:04:20

标签: mysql sql

我希望按月在一周内对数据进行分组
这是我的sql代码:

SELECT IFNULL(SUM(b.totmom), 0) AS mom,  
  a.monthLead
FROM (SELECT 'Week 1' monthLead, 
    1 monthOrder UNION ALL SELECT 'Week 2' monthLead, 
    2 monthOrder UNION ALL SELECT 'Week 3' monthLead, 
    3 monthOrder UNION ALL SELECT 'Week 4' monthLead, 
    4 monthOrder UNION ALL SELECT 'Week 5' monthLead, 
    5 monthOrder) a 
LEFT JOIN (SELECT b.momDate, COUNT(b.momID) as totmom, 
  FLOOR(((DAY(b.momDate) - 1) / 7) + 1) week
FROM log_mom b 
WHERE YEAR(b.momDate)='2019'
  AND MONTH(b.momDate)='06' 
  AND FLOOR(((DAY(b.momDate) - 1) / 7) + 1) IN ('Week 1','Week 2','Week 3','Week 4','Week 5') 
group by week ) b ON a.monthLead = FLOOR(((DAY(b.momDate) - 1) / 7) + 1) GROUP BY a.monthLead ORDER BY a.monthOrder");

样本数据表log_mom:

momID momDate
 1    2019-06-01
 2    2019-06-03
 3    2019-06-03
 4    2019-06-07
 5    2019-06-12
 6    2019-06-14
 7    2019-06-23
 8    2019-06-24
 9    2019-06-29
 10   2019-06-31

结果是:

mom monthLead
 0   Week 1

我如何获得这样的结果:

mom monthLead
 4   Week 1
 2   Week 2
 0   Week 3
 2   Week 4
 2   Week 5

1 个答案:

答案 0 :(得分:1)

我认为在monthOrder条件下,整数值(monthLead)和字符串(JOIN)之间存在混淆,并且主查询中缺少GROUP BY a.monthLead,并且过滤条件AND FLOOR(((DAY(b.momDate) - 1) / 7) + 1)...似乎是错误的:

SELECT IFNULL(SUM(b.totmom), 0) AS mom, a.monthLead
  FROM (
        SELECT 'Week 1' monthLead, 1 monthOrder UNION ALL
        SELECT 'Week 2' monthLead, 2 monthOrder UNION ALL
        SELECT 'Week 3' monthLead, 3 monthOrder UNION ALL
        SELECT 'Week 4' monthLead, 4 monthOrder UNION ALL
        SELECT 'Week 5' monthLead, 5 monthOrder                        
        ) a
  LEFT JOIN (SELECT b.momDate,
                    COUNT(b.momID) as totmom,
                    FLOOR(((DAY(b.momDate) - 1) / 7) + 1) week
               FROM log_mom b
              WHERE YEAR(b.momDate) = '2019'
                AND MONTH(b.momDate) = '06'
             -- AND FLOOR(((DAY(b.momDate) - 1) / 7) + 1) IN ('Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5')
              GROUP BY week) b
    ON a.monthOrder = FLOOR(((DAY(b.momDate) - 1) / 7) + 1)
 GROUP BY a.monthLead;

Demo