My table:
| Column1 | Date |
| ------------ | ------------ |
| Value1 | 1-Feb |
| Value2 | 1-Feb |
| Value2 | 2-Feb |
| Value3 | 2-Feb |
| Value1 | 3-Feb |
| Value2 | 3-Feb |
| Value4 | 3-Feb |
Expected Output:
Column1 | Date | Status |
---|---|---|
Value1 | 1-Feb | Added |
Value2 | 1-Feb | Added |
Value1 | 2-Feb | Closed |
Value3 | 2-Feb | Added |
Value1 | 3-Feb | Added |
Value3 | 3-Feb | Closed |
Value4 | 3-Feb | Added |
How to get the records that have been added or closed between certain dates in a table in SQL
I'm executing an except command between each date and vice versa then inserting data into a table. Is there any way I can achieve the desired output with a single query?
I'm currently using this solution.
SELECT column1, 'Added' AS Status FROM mytable WHERE date = '2023-02-03' EXCEPT SELECT column1 FROM mytable WHERE date = '2023-02-02'
UNION
SELECT column1, 'Closed' AS Status FROM mytable WHERE date = '2023-02-02' EXCEPT SELECT column1 FROM mytable WHERE date = '2023-02-03'
1条答案
按热度按时间6ie5vjzr1#
You can do it by generating the upcoming days for every column with no upcoming day, then with
left join
you can get the Status.Demo here