我有以下记录:
Id Date MondayMorning MondayEvening TuesdayMorning TuesdayEvening and so on
1 2012-01-01 2 3 2 2
2 2012-01-02 2 2 2 2
我想将记录 1 分成两条记录,因为 mondaymorning 和 mondayevening 的状态不一样。如果状态相同,则什么也不做。
我期望的结果:
Id Date MondayMorning MondayEvening TuesdayMorning TuesdayEvening
1 2012-01-01 2 NULL 2 2
1 2012-01-01 NULL 3 NULL NULL
2 2012-01-02 2 2 2 2
请记住,其他日子也可能有所不同。
我已经有一个查询,但是,印楝一些变化。请参阅 SQL Fiddle上的查询。您可以在此处看到的输出是出错的情况。对于周二晚上和周一晚上,我期待 2。
SQL Fiddle 上的信息是:
Declare @t Table(Id int identity,[Date] Datetime,MondayMorning Int,MondayEvening Int,TuesdayMorning Int,TuesdayEvening Int)
Insert Into @t Select '2012-01-01',0,2,0,2
SELECT id
,date
,MondayMorning
,(CASE WHEN MondayEvening <> MondayMorning THEN NULL ELSE MondayEvening END) AS MondayEvening
,TuesdayMorning
,(CASE WHEN TuesdayEvening <> TuesdayMorning THEN NULL ELSE TuesdayEvening END) AS TuesdayEvening
FROM @t
UNION ALL
SELECT id
,date
,NULL AS MondayMorning
,(CASE WHEN MondayEvening = MondayMorning THEN NULL ELSE MondayEvening END) AS MondayEvening
,NULL AS TuesdayMorning
,(CASE WHEN TuesdayEvening = TuesdayMorning THEN NULL ELSE TuesdayEvening END) AS TuesdayEvening
FROM @t
WHERE --MondayMorning <> MondayEvening
--OR TuesdayMorning <> TuesdayEvening
MondayMorning <> MondayEvening
AND (MondayMorning != 0 and MondayEvening != 0)
OR TuesdayMorning <> TuesdayEvening
AND (TuesdayEvening != 0 and TuesdayMorning != 0)