我有一个定义表-def
event_data
及其交易记录在差异表-event
中Id Device Location
1 GGHY199 USA
12 DFGHY71 India
145 APPHY75 USA
我希望输出为 对于每一天,所有三个设备均应显示,如果没有事务发生,则应显示为null,我认为这是日期列中的月份的第一个日期。 喜欢,
eventid deviceid event date
123 12 Login 12-01-2019
32 12 Unreachable 18-02-2019
223 145 Unreachable 19-02-2019
334 1 DOWN 01-03-2019
当前我正在做
eventid deviceid event date
null 1 null 01-01-2019
123 12 Login 12-01-2019
null 145 null 01-01-2019
null 1 null 01-02-2019
32 12 Unreachable 18-02-2019
223 145 Unreachable 19-02-2019
334 1 DOWN 01-03-2019
null 12 null 01-03-2019
null 145 null 01-03-2019
我显然没有得到我想要的东西。
谢谢!
答案 0 :(得分:1)
假设您有一个有效的日历表来存放所需的所有日期(通过select union all表t模拟),则可以尝试在calendare和其他表之间使用左联接
select t.date, e.eventid, e.device, e.event, d.device
from (
select '2019-01-01' date
union all
select '2019-01-02'
union all
select '2019-01-03'
.....
union all
select '2019-03-31'
) t
left event e on t.date = e.event
left join device d on e.device = d.id
答案 1 :(得分:0)
您似乎正在追寻类似的东西...
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(event_id SERIAL PRIMARY KEY
,device_id INT NOT NULL
,event VARCHAR(12) NOT NULL
,date DATE NOT NULL
);
INSERT INTO my_table VALUES
(123, 12,'Login','2019-01-12'),
( 32, 12,'Unreachable','2019-02-18'),
(223,145,'Unreachable','2019-02-19'),
(334, 1,'DOWN','2019-03-01');
SELECT DISTINCT z.event_id
, x.device_id
, z.event
, y.date
FROM my_table x
JOIN my_table y
LEFT
JOIN my_table z
ON z.device_id = x.device_id
AND z.date = y.date
ORDER
BY date
, device_id;
+----------+-----------+-------------+------------+
| event_id | device_id | event | date |
+----------+-----------+-------------+------------+
| NULL | 1 | NULL | 2019-01-12 |
| 123 | 12 | Login | 2019-01-12 |
| NULL | 145 | NULL | 2019-01-12 |
| NULL | 1 | NULL | 2019-02-18 |
| 32 | 12 | Unreachable | 2019-02-18 |
| NULL | 145 | NULL | 2019-02-18 |
| NULL | 1 | NULL | 2019-02-19 |
| NULL | 12 | NULL | 2019-02-19 |
| 223 | 145 | Unreachable | 2019-02-19 |
| 334 | 1 | DOWN | 2019-03-01 |
| NULL | 12 | NULL | 2019-03-01 |
| NULL | 145 | NULL | 2019-03-01 |
+----------+-----------+-------------+------------+
答案 2 :(得分:0)
使用CTE table
,我们可以创建日期,然后将它们与事件表关联起来。
with t0 (i) as (select 0 union all select 0 union all select 0),
t1 (i) as (select a.i from t0 a ,t0 b ),
t2 (i) as (select a.i from t1 a ,t1 b ),
t3 (srno) as (select row_number()over(order by a.i) from t2 a ,t2 b ),
tbldt(dt) as (select dateadd(day,t3.srno-1,'01/01/2019') from t3)
select eventid, deviceid, event, tbldt.dt
from tbldt
left join event e on e.date = tbldt.dt
left join def d on e.deviceid = d.id
where tbldt.dt <= (select max(date) from event)