[英]Generate days from date range sql
I need to generate the days between two dates in sql like this: 我需要像这样在sql中生成两个日期之间的日期:
generate days from date range 从日期范围生成天
Im using this query: 我正在使用此查询:
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
Works well but this generates always 1000 days. 效果很好,但这总是产生1000天。 How can i generate any other number of days like 365?
我如何生成其他天数,例如365?
You could add a limit clause (and an order by) 您可以添加一个限制条款(和一个命令)
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
Or, if you are allowed to create temporary tables, in a more readable fashion - and extendable to 10,000 integers or more quite easily: 或者,如果允许您以更易读的方式创建临时表,并且可以很容易地扩展到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.