我创建了一个临时表,我想将其取消,但我不断收到如下错误消息: 消息156,第15级,状态1,第196行 关键字'附近的语法不正确
我的临时表如下:
档案订单号T_Code Routine_Labour Variable_Labour
我想把它转到下面:
我使用了以下脚本:
Select
Dossier,
Order_Number,
T_Code,
Labour_Type,
Amount
from
#LabourSplit
Unpivot
(
Amount for Labour_Type in (Routine_Labour, Variable_Labour)
) as LabourSplit_U
一旦我运行此脚本,就会弹出错误消息。即使我在临时表和脚本中注释掉了两列,但仍然存在错误消息。
Select
Dossier,
--Order_Number,
--T_Code,
Labour_Type,
Amount
from
#LabourSplit
Unpivot
(
Amount for Labour_Type in (Routine_Labour, Variable_Labour)
) as LabourSplit_U
答案 0 :(得分:2)
我认为CROSS APPLY VALUES比UNPIVOT
更容易使用和理解SELECT Dossier
,Order_Number
,T_Code
,Labour_Type
,Amount
FROM #LabourSplit
CROSS APLLY (
VALUES (Routine_Labour, 'Routine_Labour')
,(Variable_Labour, 'Variable_Labour')
) AS CA1(Amount, Labour_Type)
答案 1 :(得分:1)
试试这个:
Select
Dossier,
Order_Number,
T_Code,
Labour_Type,
Amount
FROM
(
Select
Dossier,
Order_Number,
T_Code,
Routine_Labour,
Variable_Labour
from #LabourSplit
) a
Unpivot
(
Amount for Labour_Type in (Routine_Labour, Variable_Labour)
) as LabourSplit_U
结果:
| DOSSIER | ORDER_NUMBER | T_CODE | LABOUR_TYPE | AMOUNT |
|---------|--------------|--------|-----------------|--------|
| 1234 | 5678 | 1 | Routine_Labour | 10 |
| 1234 | 5678 | 1 | Variable_Labour | 20 |
| 1234 | 3434 | 1 | Routine_Labour | 20 |
| 1234 | 3434 | 1 | Variable_Labour | 70 |
| 1234 | 5671 | 1 | Routine_Labour | 30 |
| 1234 | 5671 | 1 | Variable_Labour | 10 |
| 1234 | 3422 | 1 | Routine_Labour | 40 |
| 1234 | 3422 | 1 | Variable_Labour | 40 |
| 1234 | 1122 | 1 | Routine_Labour | 11 |
| 1234 | 1122 | 1 | Variable_Labour | 30 |
但是,据我所知,UNPIVOT在完整版本的SQL Server中受支持。如果您有紧凑版或其他免费版本,则需要使用UNION ALL
:
Select
Dossier,
Order_Number,
T_Code,
'Routine_Labour' AS Labour_Type,
Routine_Labour AS Amount
FROM LabourSplit
UNION ALL
Select
Dossier,
Order_Number,
T_Code,
'Variable_Labour' AS Labour_Type,
Variable_Labour AS Amount
FROM LabourSplit
ORDER BY 1,2,3
选中此SQL Fiddle
结果:
| DOSSIER | ORDER_NUMBER | T_CODE | LABOUR_TYPE | AMOUNT |
|---------|--------------|--------|-----------------|--------|
| 1234 | 1122 | 1 | Routine_Labour | 11 |
| 1234 | 1122 | 1 | Variable_Labour | 30 |
| 1234 | 3422 | 1 | Variable_Labour | 40 |
| 1234 | 3422 | 1 | Routine_Labour | 40 |
| 1234 | 3434 | 1 | Routine_Labour | 20 |
| 1234 | 3434 | 1 | Variable_Labour | 70 |
| 1234 | 5671 | 1 | Variable_Labour | 10 |
| 1234 | 5671 | 1 | Routine_Labour | 30 |
| 1234 | 5678 | 1 | Routine_Labour | 10 |
| 1234 | 5678 | 1 | Variable_Labour | 20 |