让我们说我有一个表,上面有这样的数据...
[date of event] [event type]
1/1 A
1/1 B
1/3 A
1/4 B
1/7 B
1/7 A
1/15 A
今天是1/15
是否有办法查看事件是否在上周而不是在本周发生?
例如,“ A”在本周和上周(1/15和1/7)都发生了...但是,“ B”仅在上周(仅1/7)发生了。理想情况下,我能够得到诸如“ B”这样的查询的答案。
我已经花了几天时间,但我完全陷入困境。谢谢您的宝贵时间。
答案 0 :(得分:1)
这应该很容易通过左连接适当的视图(子查询)来解决:
select @start_a:='2019-01-02';
select @end_a:='2019-01-08';
select @start_b:='2019-01-09';
select @end_b:='2019-01-15';
-- these could be e.g. DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY)
SELECT DISTINCT A.event_type
FROM (
SELECT DISTINCT event_type
FROM table_name
WHERE date_of_event>=@start_a AND date_of_event<=@end_a
) AS A
LEFT JOIN (
SELECT DISTINCT event_type
FROM table_name
WHERE date_of_event>=@start_b AND date_of_event<=@end_b
) AS B
ON A.event_type=B.event_type
WHERE B.event_type IS NULL
;
说明:我们将一周中的所有事件都选择为A,将比较周中的所有事件都选择为B。然后从A中选择在比较周中没有对应项的那些行。
答案 1 :(得分:1)
如果(显着)减少打字(和/或提高性能)是您的事,那么您可以考虑以下事项...
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(dt DATE NOT NULL
,event_type CHAR(1) NOT NULL
,PRIMARY KEY(dt,event_type)
);
INSERT INTO my_table VALUES
('2019-01-01','A'),
('2019-01-01','B'),
('2019-01-03','A'),
('2019-01-04','B'),
('2019-01-07','B'),
('2019-01-07','A'),
('2019-01-15','A');
所以,让我们找到没有重复的事件...
SELECT DISTINCT x.*
FROM my_table x
JOIN my_table y
ON y.event_type = x.event_type
AND y.dt = '2019-01-15'
WHERE x.dt BETWEEN '2019-01-15' - INTERVAL 2 WEEK AND '2019-01-15' - INTERVAL 1 WEEK;
+------------+------------+
| dt | event_type |
+------------+------------+
| 2019-01-01 | A |
| 2019-01-03 | A |
| 2019-01-07 | A |
+------------+------------+
...然后是相反的...
SELECT DISTINCT x.event_type
FROM my_table x
LEFT
JOIN my_table y
ON y.event_type = x.event_type
AND y.dt = '2019-01-15'
WHERE x.dt BETWEEN '2019-01-15' - INTERVAL 2 WEEK AND '2019-01-15' - INTERVAL 1 WEEK
AND y.dt IS NULL;
+------------+
| event_type |
+------------+
| B |
+------------+