SQL将重复值移动到新列

时间:2014-01-06 21:30:38

标签: sql sql-server pivot

我在这里发现了一个类似的问题:Move duplicated values into unique columns,但我不确定这对我有用。

提供的数据如下所示:

email_address    barcode           value    
1@aol.com        9X3BZBK9CPWVDT16  25
123@verizon.net  9X3L6RD1Y83J8Z6Q  50
123@verizon.net  9X3PWCQRNX2CNJBC  50
2@naver.com      9X3N438B6TZYRD1N  50
3@msn.com        9X3PVFJ2N3C2DNW6  25
456@yahoo.com    9X3BCJ3YXFQ1RFGU  50
456@yahoo.com    9X3L1DVG89CGDBB0  25

但我希望看起来像这样:

EMAIL_ADDRESS    BURNED_BARCODE1    value1    BURNED_BARCODE2    value2        
1@aol.com        9X3BZBK9CPWVDT16   25
123@verizon.net  9X3L6RD1Y83J8Z6Q   50        9X3PWCQRNX2CNJBC   50
2@naver.com      9X3N438B6TZYRD1N   50
3@msn.com        9X3PVFJ2N3C2DNW6   25
456@yahoo.com    9X3BCJ3YXFQ1RFGU   50        9X3L1DVG89CGDBB0   25

我正在尝试将重复的优惠券代码和值合并到BARCODE_2和value2中。我已经考虑了数据透视表,但我似乎无法使逻辑工作。

有什么想法?提前谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用ROW_NUMBER()功能和自我加入:

;WITH cte AS (SELECT *, ROW_NUMBER()OVER(PARTITION BY email_address ORDER BY barcode) AS RN
              FROM Table1)
SELECT a.email_address, a.barcode, a.value, b.barcode AS barcode2, b.value AS value2
FROM cte a
LEFT JOIN cte b
 ON a.email_address = b.email_address
  AND a.RN = b.RN -1
WHERE a.RN = 1

演示:SQL Fiddle

更新:您可以添加第3个:

;WITH cte AS (SELECT *, ROW_NUMBER()OVER(PARTITION BY email_address ORDER BY barcode) AS RN
              FROM Table1)
SELECT a.email_address, a.barcode, a.value
     , b.barcode AS barcode2, b.value AS value2
     , c.barcode AS barcode3, c.value AS value3
FROM cte a
LEFT JOIN cte b
 ON a.email_address = b.email_address
  AND a.RN = b.RN -1
LEFT JOIN cte c
 ON a.email_address = c.email_address
  AND a.RN = c.RN -2
WHERE a.RN = 1

演示:SQL Fiddle

如果超过2,PIVOT答案可能更合适。