SQL按日期分割mutilple

时间:2015-10-29 01:41:35

标签: sql-server

我们说我在表中有这些值

| Start Date              | End date                   |Other Value
---------------------------------------------------------------------
| 2015-01-07 01:00:00.000 | 2015-01-08 04:00:00.000    | Yes
| 2015-01-08 10:00:00.000 | 2015-01-10 20:00:00.000    | No

我想编写一个select语句,它应该给我一些结果:

|Date        | Start Date   | End date     |Other Value
-----------------------------------------------------------
|2015-01-07  | 01:00:00.000 |              | Yes
|2015-01-08  |              | 04:00:00.000 | Yes
|2015-01-08  | 10:00:00.000 |              | No
|2015-01-10  |              | 20:00:00.000 | No

有没有办法在T-SQL中执行此操作?

我使用的是SQL Server 2008 R2。

3 个答案:

答案 0 :(得分:0)

你可以这样做......

SQL Fiddle

WITH cte AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rn,startdate,enddate, othervalue  FROM yourtable
)
,cte1 AS
(
SELECT rn,cast(startdate AS DATE) AS [date]
         ,CAST(startdate AS TIME) AS [Start Date]
         ,null AS [End date]
         , othervalue 
FROM cte
UNION all
SELECT rn,cast(Enddate AS DATE) AS [date]
          ,null AS [Start Date]
          ,CAST(Enddate AS TIME) AS [End date], 
          othervalue 
FROM cte
)

sELECT * FROM CTE1 ORDER BY RN,[Start Date] desc

答案 1 :(得分:0)

您可以使用UNION ALL和ROW_NUMBER()来订购结果,如下所示:

WITH CTE AS
(
   SELECT *,
      ROW_NUMBER() OVER(ORDER BY (SELECT NULL) AS rownum
   FROM Your_Table
)
SELECT
   rownum,
   CAST([Start date] AS DATE) AS [Date],
   CAST([Start date] AS DATE) AS [Start date],
   NULL AS [End date],
   [Other Value]
FROM CTE

UNION ALL

SELECT
   rownum,
   CAST([End date] AS DATE) AS [Date],
   NULL AS [Start date],
   CAST([End date] AS DATE) AS [End date],       
   [Other Value]
FROM CTE

ORDER BY rownum

答案 2 :(得分:0)

使用CROSS APPLYVALUES

SQL Fiddle

SELECT
    x.*, t.OtherValue
FROM tbl t
CROSS APPLY(VALUES
    (CAST(StartDate AS DATE), CAST(StartDate AS TIME), NULL),
    (CAST(EndDate AS DATE), NULL, CAST(EndDate  AS TIME))
)x(Date, StartDate, EndDate)

此方法仅扫描表格一次。