0

我在 Sql 表中有两列名为“下一个计划日期”和“预期计划日期”。我真正想要的是组合两列而不是串联,只是将它们组合在另一行下方。

我试过 unPivot 但它不起作用。任何建议请

select [Asset / Location],[Department Name], Future_Scheduled_Date from merge2_ernie Unpivot(Future_Scheduled_Date for [Department Name] in (select Distinct [Department Name] from merge2_ernie))作为示例

我的数据现在看起来像这样

**Department_Name**    **Next_Schedule_Date**   **Expected_Scheduled_Date**

Dept1                    Aug 2019             Sep 2019
Dept1                    Oct 2019             Nov 2019
Dept2                    Jan 2019             Mar 2019
Dept3                    Nov 2019             Jan 2020
Dept4                    Apr 2019             Sep 2019
Dept5                    Jun 2019             Jul 2019

我希望数据如下所示

Department_Name    Future_Schedule_Date   

Dept1               Aug 2019            
Dept1               Sep 2019           
Dept1               Oct 2019          
Dept1               Nov 2019           
Dept2               Jan 2019
Dept2               Mar 2019
Dept3               Nov 2019
Dept3               Jan 2020
Dept4               Apr 2019             
Dept4               Sep 2019
Dept5               Jun 2019
Dept5               Jul 2019
4

2 回答 2

1

你需要 UNPIVOT 而不是 PIVOT

CREATE TABLE #dept
(
    dept VARCHAR(5),
    nextdate VARCHAR(10),
    expecteddate VARCHAR(10) 
)

INSERT INTO #dept(dept, nextdate, expecteddate)
VALUES
('Dept1','Aug 2019','Sep 2019'),
('Dept1','Oct 2019','Nov 2019'),
('Dept2','Jan 2019','Mar 2019'),
('Dept3','Nov 2019','Jan 2020'),
('Dept4','Apr 2019','Sep 2019'),
('Dept5','Jun 2019','Jul 2019');

-- unpivot the data into key value pairs
SELECT dept, val
FROM 
(
SELECT *
from #dept
) a
UNPIVOT
(
val
FOR name IN ([nextdate],[expecteddate])
) u
于 2019-07-18T15:51:02.983 回答
0

您可以使用apply

select Department_Name, Future_Schedule_Date
from table t cross apply
     ( values (Next_Schedule_Date), (Expected_Scheduled_Date) 
     ) tt(Future_Schedule_Date)
order by Department_Name, Future_Schedule_Date;
于 2019-07-18T15:52:40.170 回答