I am new to the sql world and trying to archive a certain result.
I have two tables: Table A contains, among other things, the following columns: Market_ID, Date, Event
| Market_ID | Date | Event |
| -------- | -------------- |------ |
| 1 | 2023-01-06 | F |
| 1 | 2023-04-07 | F |
| 2 | 2023-01-06 | F |
where the column event also contains other strings than ‘F’, but only ‘F’ is relevant for me. In addition, the column date does not contain all dates within a year. It only has an entry if there is an event on this day.
Table B is a date table just containing all dates in different formats within a year from the past and future
| Date_Day | Date_Week |
| ---------- | -------------- |
| 2023-01-01 | 2023/01 |
| 2023-01-02 | 2023/01 |
| 2023-01-03 | 2023/01 |
| 2023-01-04 | 2023/01 |
| 2023-01-05 | 2023/01 |
| 2023-01-06 | 2023/01 |
| ... | ... |
My expected output should be a table containing all dates and an additional column whether there was an Event F on that day or not:
| Market_ID | Date | Is_EVENT_F|
| -------- | -------------- |---------- |
| 1 | 2023-01-01 | 0 |
| 1 | 2023-01-02 | 0 |
| 1 | 2023-04-03 | 0 |
| 1 | 2023-04-04 | 0 |
| 1 | 2023-04-05 | 0 |
| 1 | 2023-01-06 | 1 |
I have tried using either an right or outer join but in both cases, the result was not correct.
5
Answers
Subquery
markets
gather all markets list. If markets table exisrts then use it instead.Joining this subquery and dates list generates all possible pairs market-date.
Subquery in EXISTS checks does the row with
'F'
exists for each market at each date.https://dbfiddle.uk/-CVLgaV4
But this query is obviously going to return null Market_id for the dates in which there is no record in TABLE_A.
I’ll use Inner SELECT statement:
You could try this query