如何从一个制作两个记录?

时间:2012-11-02 08:31:59

标签: sql sql-server stored-procedures

我有以下记录:

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

我希望在两个记录中分成记录1,因为星期一和星期一的状态不一样。如果状态相同则不做任何事情。

我期待的结果:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

enter image description here

答案 3 :(得分:-2)

Select * from empmas where compcd=1 and empcd =0001 connect by level <=2;

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