表示されていない場所フィールドがある場合は、各列に入力する意味を区別できます
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;