我怎么能得到0没有使用mysql的记录?

时间:2012-11-05 12:25:54

标签: mysql sql

我是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

1 个答案:

答案 0 :(得分: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