我在oracle SQL中要求将多行转换为单行。
以下是示例:
Empid Ele_name Inp_name Inp_Value EntryId Start_date End Date
123 LW MA 1637 100000104856397 06-Nov-17 31-Dec-12
123 LW CA Y 100000104856397 06-Nov-17 31-Dec-12
143 LW MA 1637 100000104856504 06-Nov-17 31-Dec-12
143 LW CA Y 100000104856504 06-Nov-17 31-Dec-12
144 MTS AA 1000 300002685277016 12-Dec-17 31-Dec-12
144 MTS CA Y 300002685277016 12-Dec-17 31-Dec-12
144 LW CA Y 300002685277012 06-Nov-17 31-Dec-12
144 LW AA 200 300002685277012 06-Nov-17 31-Dec-12
预期输出
Empid Element_name FIrstName LastName Initials Input_name1 Input_Value1 Input_name2 Input_Value2 Input_name3 Input_Value3 Input_name4 Input_Value4 Input_name5 Input_Value5 EntryId Start_date End Date
123 LW null null null MA 1637 CA Y null null null null null null 100000104856397 06-Nov-17 31-Dec-12
143 LW null null null MA 1637 CA Y null null null null null null 100000104856504 06-Nov-17 31-Dec-12
144 MTS null null null AA 1000 CA Y null null null null null null 300002685277016 12-Dec-17 31-Dec-12
144 LW null null null CA Y AA 200 null null null null null null 300002685277012 06-Nov-17 31-Dec-12
我听说这可以通过Pivot完成。但我对这个概念不熟悉。任何人都可以帮到这里。
答案 0 :(得分:0)
您需要做更多的工作才能像这样进行转动,因为转移会占用行数据并使其成为列名,但您的行数据都不会1, 2, 3, 4...
用作列名(inp_value1&lt ; - 这里的1)
你可以这样做,这可能更容易理解:
SELECT
Empid,
Ele_name,
MAX(CASE WHEN rown = 1 THEN Inp_name END) as Inp_name1,
MAX(CASE WHEN rown = 1 THEN Inp_value END) as Inp_Value1,
MAX(CASE WHEN rown = 2 THEN Inp_name END) as Inp_name2,
MAX(CASE WHEN rown = 2 THEN Inp_value END) as Inp_Value2,
MAX(CASE WHEN rown = 3 THEN Inp_name END) as Inp_name3,
MAX(CASE WHEN rown = 3 THEN Inp_value END) as Inp_Value3,
MAX(CASE WHEN rown = 4 THEN Inp_name END) as Inp_name4,
MAX(CASE WHEN rown = 4 THEN Inp_value END) as Inp_Value4,
MAX(CASE WHEN rown = 5 THEN Inp_name END) as Inp_name5,
MAX(CASE WHEN rown = 5 THEN Inp_value END) as Inp_Value5,
MAX(CASE WHEN rown = 6 THEN Inp_name END) as Inp_name6,
MAX(CASE WHEN rown = 6 THEN Inp_value END) as Inp_Value6,
EntryId,
Start_date,
End_Date
FROM
(SELECT t2.*, ROW_NUMBER() OVER(PARTITION BY EmpId, Ele_name ORDER BY 1) as rown FROM t2) d
GROUP BY
Empid,
Ele_name,
EntryId,
Start_date,
End_Date
null as input_name3..
等等或者你可以这样转动(更难理解但更紧凑):
SELECT
Empid,
Ele_name,
pvt.*,
EntryId,
Start_date,
End_Date
FROM
(SELECT t2.*, ROW_NUMBER() OVER(PARTITION BY EmpId, Ele_name ORDER BY 1) as rown
FROM t2) d
PIVOT(
MAX(inp_name) as inp_name,
MAX(inp_value) as inp_value
FOR rown in (1,2,3,4,5,6)
) pvt
但列将来自pvt.*
,名称为1_inp_name,1_inp_value ..您必须使用AS
重命名