如果您有一个未向我们展示的位置字段,可以区分每列的含义
SELECT
custcode,
MAX(CASE WHEN location = 1 THEN address END) AS location1,
MAX(CASE WHEN location = 2 THEN address END) AS location2,
MAX(CASE WHEN location = 3 THEN address END) AS location3
FROM X
GROUP BY custcode
如果您依赖行排序 SQL Server 特定答案。
这假设您有一个 ID 字段,可以从中计算“第一”行的顺序。
with X as
(
SELECT 1 AS ID, 'cust1' AS custcode, 'capitol, cebu city' AS address
UNION ALL
SELECT 2 AS ID, 'cust1' AS custcode, 'gen. maxilom, cebu city' AS address
UNION ALL
SELECT 3 AS ID, 'cust1' AS custcode, 'guadalupe, cebu city' AS address
UNION ALL
SELECT 4 AS ID, 'cust2' AS custcode, 'paknaan, mandaue city' AS address
UNION ALL
SELECT 5 AS ID, 'cust2' AS custcode, 'basak, mandaue city' AS address
UNION ALL
SELECT 6 AS ID, 'cust2' AS custcode, 'lapu-lapu city'
)
, Y AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY custcode ORDER BY ID) AS RN,
custcode,
address
FROM X
)
SELECT custcode, [1] AS location1 , [2] AS location2,[3] AS location3 FROM Y
PIVOT
(
Max(address)
FOR RN IN ([1], [2],[3])
) AS PivotTable;