Skip to content

Instantly share code, notes, and snippets.

@graemeboyd
Created April 13, 2017 14:59
Show Gist options
  • Save graemeboyd/3361bb7caf9a7df9cc1c7b6be2008759 to your computer and use it in GitHub Desktop.
Save graemeboyd/3361bb7caf9a7df9cc1c7b6be2008759 to your computer and use it in GitHub Desktop.
Pairs of sets on dates = [[128, "2017-01-01"],[128, "2017-02-01"],[128, "2017-03-01"],[128, "2017-04-01"],[128, "2017-05-01"],
[256, "2017-06-01"],[256, "2017-07-01"],[256, "2017-08-01"],[256, "2017-09-01"],[256, "2017-10-01"]]
| id | set_id | date |
| 1 | 128 | "2017-01-01"|
| 2 | 128 | "2017-02-01"|
| 3 | 128 | "2017-03-01"|
| 4 | 128 | "2017-04-01"|
| 5 | 128 | "2017-05-01"|
| 6 | 128 | "2017-06-01"|
| 7 | 128 | "2017-07-01"|
| 8 | 128 | "2017-08-01"|
| 9 | 128 | "2017-09-01"|
| 10 | 128 | "2017-10-01"|
| 11 | 256 | "2017-01-01"|
| 12 | 256 | "2017-02-01"|
| 13 | 256 | "2017-03-01"|
| 14 | 256 | "2017-04-01"|
| 15 | 256 | "2017-05-01"|
| 16 | 256 | "2017-06-01"|
| 17 | 256 | "2017-07-01"|
| 18 | 256 | "2017-08-01"|
We want to select the ids from the table for the array of pairs above AND in
a separate query, select which pairs are missing from the table.
SELECT set_dates.id FROM set_dates WHERE ROW(set_id, date) IN (
(128, '2017-01-01'),
(128, '2017-02-01'),
(128, '2017-03-01'),
(128, '2017-04-01'),
(128, '2017-05-01'),
(256, '2017-06-01'),
(256, '2017-07-01'),
(256, '2017-08-01'),
(256, '2017-09-01'),
(256, '2017-10-01'))
SELECT * FROM set_dates
RIGHT OUTER JOIN (
SELECT * FROM UNNEST(
ARRAY[128,128,128,128,128,256,256,256,256,256]::integer[],
ARRAY['2017-01-01', '2017-02-01', '2017-03-01', '2017-04-01', '2017-05-01', '2017-06-01', '2017-07-01', '2017-08-01', '2017-09-01', '2017-10-01']::date[]
) AS t(set_id, date)
) AS ary
ON set_dates.date = ary.date AND set_dates.set_id = ary.set_id
WHERE id IS NULL;
@graemeboyd
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment