Back

การสร้างวันที่จากช่วงวันที่ด้วยคำสั่ง SQL

     ในการทำข้อมูลเพื่อออกรายงาน บางครั้งต้องการข้อมูลทุกวันในช่วงวันที่ที่กำหนด แต่ถ้าข้อมูลในฐานข้อมูลไม่ได้มีทุกวัน การดึงข้อมูลจากฐานข้อมูลจะทำให้วันที่ที่ไม่มีข้อมูลหายไป ซึ่งจะทำให้รายงานไม่ถูกต้อง ในการนี้จึงได้ทำคิวรี่สำหรับสร้างวันที่จากช่วงวันที่เราต้องการ ดังตัวอย่างด้านล่าง

— mysql
select f.split_date from 
(select adddate(‘2024-08-01’,e.i*10000 + d.i*1000 + c.i*100 + b.i*10 + a.i) split_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) a,
(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) b,
(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) c,
(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) d,
(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) e) f
where f.split_date between ‘2024-08-01’ and ‘2024-08-08’;
 
— sql server
declare @start_date date = ‘2024-08-01’
declare @end_date date = ‘2024-08-08’
select top 
    (datediff(day, @start_date, @end_date) + 1)
    split_date = dateadd(day, row_number() over(order by a.object_id) – 1, @start_date)
from sys.all_objects a
cross join sys.all_objects b;
 
— oracle
select to_char(date ‘2024-08-01’ + level – 1, ‘yyyy-mm-dd’) as split_date 
from dual
connect by level <= date ‘2024-08-08’ – date ‘2024-08-01’ + 1;

จากภาพ เป็นตัวอย่างผลการสร้างวันที่จากช่วงวันที่ 2024-08-01 ถึงวันที่ 2024-08-08