Suppose I have data available for 09-02-2020 and I want last 8 days data between 01-02-2020 to 09-02-2020 but if there is no data available for 01-02-2020 to 08-02-2020 so then just print " - " at the place of data.
I want the query for this scenario.
Expected Output -:
|Date counts|
|09-02-2020 15 |
|08-02-2020 - |
|07-02-2020 - |
|06-02-2020 - |
|05-02-2020 - |
|04-02-2020 - |
|03-02-2020 - |
|02-02-2020 - |
|01-02-2020 - |
Assuming that data is stored in Test table with date and value. Try below query:
select t1.selected_date,case when t2.val is null then "-" else convert(t2.val,char) end as val from
(select selected_date from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2020-02-01' and '2020-02-09'
)
t1
left join test t2 on t1.selected_date=t2.date order by t1.selected_date desc;
Output:
2020-02-09 -
2020-02-08 -
2020-02-07 -
2020-02-06 -
2020-02-05 -
2020-02-04 1
2020-02-03 6
2020-02-02 5
2020-02-01 1
If the data type of date column is varchar
then you can convert it using CONVERT(column_name as date)
and above will use the date format as YYYY-MM-DD
so you will have to change the date format using DATE_FORMAT .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.