我正在努力实现以下目标:
我有一个包含这样数据的表:
INSERT INTO `control_leads` (`LeadID`, `Type`, `Business`, `Date`, `Multiplier`, `UserID`)
VALUES
(1026, 'Bags', 'AB', '2017-01-18', 1, 11),
(1030, 'Ice Scraper', 'AB', '2017-01-18', 1, 8),
(1029, 'Drawstring ', 'AB', '2017-01-18', 1, 8),
(1028, 'Umbrellas', 'AB', '2017-01-18', 1, 11),
(1027, 'Lanyards', 'LP', '2017-01-18', 2, 11),
(1025, 'Bags', 'AB', '2017-01-18', 2, 8),
(1031, 'Lanyards', 'LP', '2017-01-18', 2, 8),
(1018, 'Lanyards', 'LP', '2017-01-17', 1, 8),
(1017, 'Bags', 'AB', '2017-01-17', 1, 8),
(1023, 'Hand Warmer', 'AB', '2017-01-17', 1, 8),
(1020, 'Lanyards', 'LP', '2017-01-17', 2, 11),
(1021, 'Pens', 'AB', '2017-01-17', 1, 11),
(1022, 'Bags', 'AB', '2017-01-17', 1, 8),
(1024, 'Headphones', 'AB', '2017-01-17', 1, 11),
(1007, 'Balls', 'AB', '2017-01-16', 1, 8),
(1008, 'Lanyards', 'LP', '2017-01-16', 2, 8),
(1009, 'Mugs', 'AB', '2017-01-16', 1, 11),
(1010, 'Bags', 'AB', '2017-01-16', 1, 8),
(1011, 'Bags', 'AB', '2017-01-16', 1, 11),
(1013, 'Phone/Table', 'AB', '2017-01-16', 1, 8),
(1015, 'Pens', 'AB', '2017-01-16', 1, 11),
(1016, 'Selfie Stic', 'AB', '2017-01-16', 1, 8);
这是我的SQL查询:
SELECT IFNULL( SUM(Multiplier), 0) AS val, control_leads.Date AS date
FROM control_leads
WHERE Date > '2017-01-04'
GROUP BY control_leads.Date
ORDER BY date ASC
结果:
10 2017-01-05
6 2017-01-06
8 2017-01-09
14 2017-01-10
9 2017-01-11
14 2017-01-12
10 2017-01-13
10 2017-01-16
8 2017-01-17
10 2017-01-18
但我试图获得这周的价值,但也包括上周的比较
像这样:
val1 week1 val2 week2
10 2017-01-05 14 2017-01-12
6 2017-01-06 10 2017-01-1
8 2017-01-09 10 2017-01-16
14 2017-01-10 8 2017-01-17
9 2017-01-11 10 2017-01-18
编辑:
我没有很好地解释,我希望白天分组,并将其与当天的上周价值进行比较。
val1 week1 val2 week2
day1 10 2017-01-05 14 2017-01-12
day2 6 2017-01-06 10 2017-01-1
day3 8 2017-01-09 10 2017-01-16
day4 14 2017-01-10 8 2017-01-17
day5 9 2017-01-11 10 2017-01-18
答案 0 :(得分:1)
这应该适用于比较上周,按天
SELECT
cl.date
, sum(cl.multiplier) val
, cl2.date last_week
, ifnull(cl2.last_week_val,0) last_week_val
, sum(cl.multiplier) - ifnull(cl2.last_week_val,0) diff
FROM control_leads cl
LEFT JOIN (select t.date, sum(t.multiplier) last_week_val from control_leads t group by t.date) cl2
ON (cl2.date = cl.date-7)
GROUP BY date
ORDER BY date;