您好我正在使用SQL,我需要一些关于下表的帮助:
ID_enterprise | ID_workplace | Service | Address | N_Workers | 1 1 X A1 50 1 1 Y A2 50 2 2 Z A3 10 2 3 X A4 5 3 4 Z A5 5
我需要这种格式:
ID_enterprise | X | Y | Z | Address1 | Address 2 | Address 3 | Address 4 | AddressN | N_Workers1 | N_Workers2 | N_Workers3 | N_WorkersN | T_Workers 1 1 1 0 A1 A2 NULL NULL NULL 50 50 NULL NULL 100 2 1 0 1 A3 A4 NULL NULL NULL 10 5 NULL NULL 15 3 0 0 1 A5 NULL NULL NULL NULL 5 0 NULL NULL 5
AddressN和N_WorkersN适用于拥有3个以上工作中心的企业(最大的有9个)。所以我认为我需要一些恐龙......
抱歉我的英语和我糟糕的解释! 谢谢!
答案 0 :(得分:1)
您可以使用PIVOT,这是使用您提供的数据子集的示例查询。
WITH input_data AS (
SELECT 1 AS id, 'X' AS service FROM DUAL
UNION ALL
SELECT 1 AS id, 'Y' AS service FROM DUAL
UNION ALL
SELECT 2 AS id, 'Z' AS service FROM DUAL
UNION ALL
SELECT 2 AS id, 'X' AS service FROM DUAL
UNION ALL
SELECT 3 AS id, 'Z' AS service FROM DUAL
)
SELECT * FROM input_data
PIVOT (
MAX(service) FOR service IN ('X' AS x, 'Y' AS y, 'Z' AS z)
)