1

我有以下记录:

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)
4

1 回答 1

1

SQL Server 2008+,VALUES用于优雅地构造子查询。

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,3,2

     SELECT t.Id, t.[Date],
            Case when MondayMorning=v.state then MondayMorning end MondayMorning,
            Case when MondayEvening=v.state then MondayEvening end MondayEvening,
            Case when TuesdayMorning=v.state then TuesdayMorning end TuesdayMorning,
            Case when TuesdayEvening=v.state then TuesdayEvening end TuesdayEvening
       FROM @t t
CROSS APPLY (select distinct State
               from (values(MondayMorning),
                           (MondayEvening),
                           (TuesdayMorning),
                           (TuesdayEvening)) v(state)) v(state)

在 SQL Server 2005 上,将VALUES()派生表替换为 SELECT .. UNION ALL,例如

CROSS APPLY (select distinct State
               from (SELECT MondayMorning UNION ALL
                     SELECT MondayEvening UNION ALL
                     SELECT TuesdayMorning UNION ALL
                     SELECT TuesdayEvening) v(state)) v(state)
于 2012-11-04T22:52:57.540 回答