Todays_Sales
表中的所有列(ID,Salesperson,Item,Type)。
我当前的查询结果显示:
ID Salesperson Item Type
---------------------------------------
75343 Mike Germain 3874 Credit
75343 Ken Johnson 2590 Cash
67850 Justin Anderson 6435 Check
67850 Mike Germain 1228 Credit
我希望我的查询结果显示:
ID Salesperson 1 Item 1 Type 1 Salesperson 2 Item 2 Type 2
----------------------------------------------------------------------
75343 Mike Germain 3874 Credit Ken Johnson 2590 Cash
67850 Justin Anderson 6435 Check Mike Germain 1228 Credit
答案 0 :(得分:0)
试试这个:
WITH
input(id,salesperson,item,type) AS (
SELECT 75343, 'Mike Germain' ,3874,'Credit'
UNION ALL SELECT 75343, 'Ken Johnson' ,2590,'Cash'
UNION ALL SELECT 67850, 'Justin Anderson',6435,'Check'
UNION ALL SELECT 67850, 'Mike Germain' ,1228,'Credit'
)
-- Common Table Expression above is just for data, don't use
-- in real query
,
-- begin WITH clause with this if selecting from table
input_w_seq AS (
SELECT
id
, ROW_NUMBER() OVER(PARTITION BY id) AS seq
, salesperson
, item
, type
FROM input
)
SELECT
id
, MAX(CASE seq WHEN 1 THEN salesperson END) AS salesperson_1
, MAX(CASE seq WHEN 1 THEN item END) AS item_1
, MAX(CASE seq WHEN 1 THEN type END) AS type_1
, MAX(CASE seq WHEN 2 THEN salesperson END) AS salesperson_2
, MAX(CASE seq WHEN 2 THEN item END) AS item_2
, MAX(CASE seq WHEN 2 THEN type END) AS type_2
FROM input_w_seq
GROUP BY
id
ORDER BY
id
;
id |salesperson_1 |item_1|type_1|salesperson_2|item_2|type_2
67,850|Justin Anderson| 6,435|Check |Mike Germain | 1,228|Credit
75,343|Mike Germain | 3,874|Credit|Ken Johnson | 2,590|Cash