2

我是 mySql 的新手。我必须根据工作日计算表格的点击次数。

这里的时间段取决于数据库。但是如果上周没有记录,那么会发生什么,它不在列表中。但我需要它为0。那么我该怎么做呢?

SELECT CASE 
    WHEN PERIOD >= NOW() - INTERVAL 4 WEEK
                AND PERIOD < NOW() - INTERVAL 3 WEEK THEN '22-28 days ago'

    WHEN PERIOD >= NOW() - INTERVAL 3 WEEK
                AND PERIOD < NOW() - INTERVAL 2 WEEK THEN '15-21 days ago'

    WHEN PERIOD >= NOW() - INTERVAL 2 WEEK
        AND PERIOD < NOW() - INTERVAL 1 WEEK THEN '8-14 days ago'

    WHEN PERIOD >= NOW() - INTERVAL 1 WEEK
                THEN 'up to 7 days ago'
           END WeekPeriod, IFNULL(count(CLICKS),0) TotalClicks

FROM TABLE

WHERE PERIOD >= NOW() - INTERVAL 4 WEEK

GROUP BY CASE 
    WHEN PERIOD >= NOW() - INTERVAL 4 WEEK
                    AND PERIOD < NOW() - INTERVAL 3 WEEK THEN '22-28 days ago'

    WHEN PERIOD >= NOW() - INTERVAL 3 WEEK
                AND PERIOD < NOW() - INTERVAL 2 WEEK THEN '15-21 days ago'

    WHEN PERIOD >= NOW() - INTERVAL 2 WEEK
                AND PERIOD < NOW() - INTERVAL 1 WEEK THEN '08-14 days ago'

    WHEN PERIOD >= NOW() - INTERVAL 1 WEEK
                THEN '01 to 7 days ago'

END
 ORDER BY WeekPeriod";

答案应该是这样的

1-7 0 
8-15 14 
16-21 34 
21-28 45
4

1 回答 1

1
SELECT uq.timespan, COALESCE(tsq.TotalClicks, 0) as Clicks FROM (
SELECT '22-28 days ago' as timespan
union SELECT '15-21 days ago'
union SELECT '8-14 days ago'
union SELECT 'up to 7 days ago'
)uq LEFT JOIN (
SELECT CASE 
    WHEN PERIOD >= NOW() - INTERVAL 4 WEEK
                AND PERIOD < NOW() - INTERVAL 3 WEEK THEN '22-28 days ago'
    WHEN PERIOD >= NOW() - INTERVAL 3 WEEK
                AND PERIOD < NOW() - INTERVAL 2 WEEK THEN '15-21 days ago'
    WHEN PERIOD >= NOW() - INTERVAL 2 WEEK
        AND PERIOD < NOW() - INTERVAL 1 WEEK THEN '8-14 days ago'
    WHEN PERIOD >= NOW() - INTERVAL 1 WEEK THEN 'up to 7 days ago'
           END WeekPeriod, 
           count(CLICKS) TotalClicks
FROM TABLE
WHERE PERIOD >= NOW() - INTERVAL 4 WEEK
GROUP BY WeekPeriod
/*ORDER BY WeekPeriod -- unnecessary, GROUP BY implicits ORDER BY*/
)tsq ON uq.timespan = tsq.WeekPeriod
于 2012-11-05T18:10:25.823 回答