Skip to content

Instantly share code, notes, and snippets.

@flaschbier
Last active April 1, 2016 01:44
Show Gist options
  • Save flaschbier/4fd65b4451884863d181535e25aff0b3 to your computer and use it in GitHub Desktop.
Save flaschbier/4fd65b4451884863d181535e25aff0b3 to your computer and use it in GitHub Desktop.
drop table "DB1";
create table "DB1" (
lid integer,
pid integer,
"Date" date,
primary key (lid)
);
insert into "DB1"(lid, pid, "Date")
values (1, 123,'2016-01-01');
insert into "DB1"(lid, pid, "Date")
values (2, 123,'2015-12-31'); -- fixed typo
drop table "DB2";
create table "DB2" (
lid integer,
lwid integer,
"Description" char(100),
"Value" float,
"Time" time,
primary key ( lid, lwid )
);
insert into "DB2"(lid, lwid, "Description", "Value", "Time")
values (1, 1, 'abc', 1.0, '08:00:00');
insert into "DB2"(lid, lwid, "Description", "Value", "Time")
values (2, 2, 'abc', 0.8, '03:00:00');
insert into "DB2"(lid, lwid, "Description", "Value", "Time")
values (2, 3, 'abc', 0.5, '06:00:00');
select * from "DB1";
select * from "DB2";
-- inner select
SELECT "PID", "Description", MAX("Time"), "Value"
FROM "DB1" SL
INNER JOIN "DB2" SLW ON SL."LID" = SLW."LID"
WHERE SL."Date" = '2015-12-31'
GROUP BY "PID", "Description", "Value";
-- returns
-- PID Description MAX(Time) Value
-- 1 123 abc 03:00:00 0.8
-- 2 123 abc 06:00:00 0.5
SELECT
*
FROM "DB1" L
INNER JOIN "DB2" LW ON L."LID" = LW."LID"
LEFT JOIN (
SELECT "PID", "Description", MAX("Time"), "Value"
FROM "DB1" SL
INNER JOIN "DB2" SLW ON SL."LID" = SLW."LID"
WHERE SL."Date" = '2015-12-31'
GROUP BY "PID", "Description", "Value"
) L1
ON L1."Description" = LW."Description"
AND L1."PID" = L."PID"
WHERE L."PID" = 123 AND L."Date" = '2016-01-01'
-- returns
-- LID PID Date
-- 1 1 123 01.01.16
-- 2 2 123 31.12.15
-- no error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment