繁体   English   中英

从日期范围SQL生成天

[英]Generate days from date range sql

我需要像这样在sql中生成两个日期之间的日期:

从日期范围生成天

我正在使用此查询:

select a.Date 
from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
    from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a

效果很好,但这总是产生1000天。 我如何生成其他天数,例如365?

您可以添加一个限制条款(和一个命令)

select a.Date 
from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
    from (select 0 as a union all select 1 union all select 2 union all 
          select 3 union all select 4 union all select 5 union all 
          select 6 union all select 7 union all select 8 union all 
          select 9) as a
    cross join (select 0 as a union all select 1 union all select 2 union all 
                select 3 union all select 4 union all select 5 union all 
                select 6 union all select 7 union all select 8 union all 
                select 9) as b
    cross join (select 0 as a union all select 1 union all select 2 union all 
                select 3 union all select 4 union all select 5 union all 
                select 6 union all select 7 union all select 8 union all 
                select 9) as c
) a 
order by 1 desc 
limit 365

或者,如果允许您以更易读的方式创建临时表,并且可以很容易地扩展到10,000个整数或更多:

CREATE TEMPORARY TABLE units(idx) 
ENGINE=MEMORY 
AS (
          SELECT 0
UNION ALL SELECT 1 
UNION ALL SELECT 2 
UNION ALL SELECT 3 
UNION ALL SELECT 4 
UNION ALL SELECT 5 
UNION ALL SELECT 6 
UNION ALL SELECT 7 
UNION ALL SELECT 8 
UNION ALL SELECT 9
);

SELECT a.the_date 
FROM (
SELECT curdate() - INTERVAL (hundreds + tens + units) DAY AS the_date
FROM       (SELECT idx      AS units    FROM units) units
CROSS JOIN (SELECT idx*  10 AS tens     FROM units) tens
CROSS JOIN (SELECT idx* 100 AS hundreds FROM units) hundreds
WHERE hundreds + tens + units < 365
) AS a
ORDER BY 1
;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM