我正在尝试输出两个日期范围作为在单个SQL查询中按第三个分组的列。查询有效,但输出的数字显着膨胀 - 查询有问题吗?
SELECT
a.channel AS channel,
SUM(b.sessions) AS 'thisYear',
SUM(c.sessions) AS 'lastYear'
FROM overview a
LEFT JOIN overview b ON
b.date= a.date
AND b.date BETWEEN '2015-01-01' AND '2015-12-31'
JOIN overview c ON
c.date= a.date
AND c.date BETWEEN '2014-01-01' AND '2014-12-31'
WHERE a.channel!=""
group by a.channel;
当前输出给出:
channel thisYear lastYear
Direct 36891 118335
Organic Search 40231 98531
Paid Search 19962 NULL
Referral 14782 17266
Social 4228 23399
但这些数字明显高于应有的数字。 有没有更好的方法呢?
由于
答案 0 :(得分:1)
SELECT
a.channel AS channel,
sum(case when date BETWEEN '2015-01-01' AND '2015-12-31' then sessions else 0 end) AS 'thisYear',
...
FROM overview a
...
更好的是,考虑使用year(datecolumn)= 2015,除非您遇到性能问题(尽管我无法想象您在包含这些内容的表中有数百万行)。