我有一张包含以下结构的表格
| ChangedDate | IDParameter | ChangedTo(位列)|
所以我需要在参数为True或False时获取时间间隔,如下面的
| IDParameter | ChangedToDate1 | ChangedToDate2 | ChangedTo(true to false || false to true)
我做了
With RankedDates As
(
Select T1.[ChangedDate], T1.ID, T1.[ChangedToValue]
, Row_Number() Over( Partition By T1.ID Order By T1.[ChangedDate] ) As Num
From [Changes] As T1
)
SELECT T1.[ID]
,T2.[ChangedToValue]
,T1.[ChangedDate] AS startDate
,T2.[ChangedDate] AS endDate
FROM [RankedDates] AS T1
Join RankedDates As T2
On T2.ID = T1.ID
And T2.Num = T1.Num + 1
And T2.[ChangedToValue] <> T1.[ChangedToValue]
Order By T2.[ChangedDate]
问题是我在这里缺少第一个和最后一个间隔。对于开始日期,它必须为NULL,如果是第一个,则为每个参数ID的最后一个间隔的endDate为NULL。我想我需要将它添加到UNION但我的麻烦我无法理解如何为每个IDParameter添加它
我不知道什么时候第一次更改了值,我不知道该值是否会在任何时候更改,所以我需要NULL或者为第一个间隔需要一些注意事项,对于最后一个间隔需要NULL或者一些maxdate。
ms sql server 2008
抱歉这么复杂的问题。示例:
08.03.2011 ID1 0 -> 1
09.03.2011 ID1 1 -> 0
09.03.2011 ID2 0 -> 1
10.03.2011 ID1 0 -> 1
10.03.2011 ID2 1 -> 0
---&GT;
NULL , 08.03.2011 ID1 is 0
NULL , 09.03.2011 ID2 is 0
08.03.2011, 09.03.2011 ID1 is 1
09.03.2011, 10.03.2011 ID2 is 1
09.03.2011, 10.03.2011 ID1 is 0
10.03.2011, NULL ID1 is 1
10.03.2011, NULL ID2 is 0
答案 0 :(得分:2)
如何使用FULL JOIN
代替JOIN
?
它能解决你的问题吗?
修改强>
我认为这应该可以随心所欲。
select isnull(T1.ID, T2.ID) as ID
,isnull(T2.[ChangedToValue], case when T1.[ChangedToValue] = 1 then 0 else 1 end) as [ChangedToValue]
,T1.[ChangedDate] as startdate
,T2.[ChangedDate] as enddate
from [RankedDates] T1
full join [RankedDates] T2
on T2.num = T1.num +1
and T2.ID = T1.ID
and T1.[ChangedToValue] <> T2.[ChangedToValue]
order by
case when T2.[ChangedDate] is null then 1 else 0 end
,T2.[ChangedDate]
关于ChangedToValue
你是对的,如果T2为空,我现在修改它以显示相反的情况。
答案 1 :(得分:1)
假设你的基表看起来如何:
ChangeDate IDParameter ChangedTo
2011-03-08 ID1 True
2011-03-09 ID1错误
2011-03-09 ID2真实
2011-03-10 ID1 True
2011-03-10 ID2错误
SELECT (SELECT TOP 1 t0.[ChangeDate] FROM [calendardb].[dbo].[Table_1] t0
WHERE t0.IDParameter = t1.IDParameter AND t0.ChangeDate < t1.ChangeDate ORDER
BY t0.ChangeDate DESC),
[ChangeDate]
,[IDParameter]
,[ChangedTo]
FROM [calendardb].[dbo].[Table_1] t1
UNION
SELECT MAX(ChangeDate) as maxd ,NULL,[IDParameter],
(SELECT ChangedTo FROM [calendardb].[dbo].[Table_1] t0 WHERE t0.ChangeDate = (SELECT MAX(ChangeDate) FROM [calendardb].[dbo].[Table_1]
GROUP BY [IDParameter] HAVING IDParameter = t1.IDParameter) AND t1.IDParameter = t0.IDParameter)
FROM [calendardb].[dbo].[Table_1] t1
GROUP BY [IDParameter]
会给你这样的结果:
NULL 2011-03-08 ID1 1
2011-03-08 2011-03-09 ID1 0
NULL 2011-03-09 ID2 1
2011-03-09 2011-03-10 ID1 1
2011-03-09 2011-03-10 ID2 0
2011-03-10 NULL ID1 1
2011-03-10 NULL ID2 0