1

我有以下记录:

Id    Date          MondayMorning  MondayEvening  TuesdayMorning, and so on
1   2012-01-01          2               3   
2   2012-01-01          2               2 

我想将记录 1 分成两条记录,因为 mondaymorning 和 mondayevening 的状态不一样。如果状态相同,则什么也不做。

我期望的结果:

Id    Date          MondayMorning  MondayEvening  TuesdayMorning
1   2012-01-01          2               NULL          2
1   2012-01-01          NULL            3             2
2   2012-01-01          2               2 

请记住,其他日子也可能有所不同。

我怎样才能做到这一点?

4

4 回答 4

4

我不完全理解您需要的输出,但以下脚本将为您提供表中的所有记录,然后是 MondayMorning 和 MondayEvening 不匹配的所有记录。

SELECT * FROM table
UNION ALL
SELECT * FROM table WHERE table.MondayMorning <> table.MondayEvening

@Ahmet 试试这个来获得列中的 NULL

SELECT id
    ,date
    ,MondayMorning
    ,(CASE WHEN table.MondayEvening <> table.MondayMorning THEN NULL ELSE MondayEvening END) AS MondayEvening
    ,TuesdayMorning
    ,(CASE WHEN table.TuesdayEvening <> table.TuesdayMorning THEN NULL ELSE TuesdayEvening END) AS TuesdayEvening
FROM table 

UNION ALL 

SELECT id
    ,date
    ,NULL AS MondayMorning
    ,MondayEvening
    ,NULL AS TuesdayMorning
    ,TuesdayEvening
FROM table
WHERE table.MondayMorning <> table.MondayEvening
OR table.TuesdayMorning <> table.TuesdayEvening
于 2012-11-02T08:48:49.503 回答
2

由于您没有指定所需的输出,因此我提出了以下内容。让我们知道您的实际输出

Declare @t Table(Id int identity,[Date] Datetime,MondayMorning Int,MondayEvening Int)
Insert Into @t Select '2012-01-01',2,3 Union All Select '2012-01-01', 2,2

;With Cte As
(Select
    Id ,
    [Date],
    MondayMorning,
    MondayEvening,
    [Status] = Case When MondayMorning = MondayEvening Then '0' Else '1' End
From @t)
Select Id,[Date],MondayMorning,MondayEvening From Cte Where [Status] = 0
Union All
Select Id,[Date],MondayMorning,Null From Cte Where [Status] = 1
Union All
Select Id,[Date],Null,MondayEvening From Cte Where [Status] = 1

在此处输入图像描述

于 2012-11-02T08:59:12.747 回答
2
select id, date, mondaymorning as monday from yourtable
union
select id, date, mondayevening as monday from yourtable

(默认情况下,联合将删除重复项)

或更笼统地说

select distinct id, [date], value from yourtable
unpivot 
(value for day in (mondaymorning, mondayevening, ....)) u
于 2012-11-02T08:47:06.540 回答
-2
Select * from empmas where compcd=1 and empcd =0001 connect by level <=2;

检索员工 0001 详细信息并创建两条该检索记录的记录。

于 2016-12-22T03:53:38.547 回答