SQL Query Startdate to Enddate

时间:2014-03-07 10:32:31

标签: sql

我有一张表(例如 TableA ),就像这样

|名称|开始|结束日期|
| ---------------------------------------------- |
| a | 2014-02-26 | 2014-02-28 |
| b | 2014-03-05 | 2014-03-06 |

如果我想低于结果。请帮忙怎么做?

|名称|日期|
| --------------------------- |
| a | 2014-02-26 |
| a | 2014-02-27 |
| a | 2014-02-28 |
| b | 2014-03-05 |
| b | 2014-03-06 |

谢谢。

3 个答案:

答案 0 :(得分:1)

在Oracle中,它有点棘手:

SELECT distinct b.name, trim(regexp_substr(b.dates, '[^,]+', 1, LEVEL)) day
  FROM 
  (
    select a.name name,(select WM_CONCAT(a.startdate + rownum -1)  from all_objects  where rownum <=    a.enddate - a.startdate + 1) dates
    from TableA a
  ) b
CONNECT BY LEVEL <= length(b.dates) - length(REPLACE(b.dates, ',', ''))+1
order by 1,2;

内部查询以逗号分隔的字符串为每个名称生成天数。外部只是将String拆分成几行。

答案 1 :(得分:0)

在SQL Server中,可以使用CTE如下

来实现
;WITH cte(name, Startdate,Enddate)
AS
(  
    SELECT name, Startdate,Enddate FROM your_table
    UNION ALL
    SELECT name, DATEADD(dd, 1,Startdate),Enddate FROM CTE 
    WHERE Startdate < Enddate
)
SELECT * FROM cte ORDER BY name

以下是SQL Fiddle

的代码

答案 2 :(得分:-1)

这是一种简单的方法

select name, startdate from test_table
UNION ALL 
select name, enddate from test_table
order by 2 desc