转换不一致

时间:2014-02-05 12:12:12

标签: sql oracle

鉴于表A具有以下数据:

+----------+-------+
| Supplier | buyer |
+----------+-------+
| A        |     1 |
| A        |     2 |
| B        |     3 |
| B        |     4 |
| B        |     5 |
+----------+-------+

我的问题是,我可以转置第二列,以便结果表格如下:

+----------+--------+--------+--------+
| Supplier | buyer1 | buyer2 | buyer3 |
+----------+--------+--------+--------+
| A        |      1 |      2 |        |
| B        |      3 |      4 |      5 |
+----------+--------+--------+--------+

假设买家的最大数量为三个。

2 个答案:

答案 0 :(得分:4)

您可以使用公用表格表达式为每个买方在供应商中提供订单,然后只需执行常规案例将其放入列中;

WITH cte AS (
  SELECT supplier, buyer, 
    ROW_NUMBER() OVER (PARTITION BY supplier ORDER BY buyer) rn
  FROM Table1
)
SELECT supplier, 
       MAX(CASE WHEN rn=1 THEN buyer END) buyer1,
       MAX(CASE WHEN rn=2 THEN buyer END) buyer2,
       MAX(CASE WHEN rn=3 THEN buyer END) buyer3
FROM cte
GROUP BY supplier;

An SQLfiddle to test with

答案 1 :(得分:2)

您可以考虑使用PIVOT条款:

select *
from (
  select supplier, buyer, row_number() over (partition by supplier order by buyer) as seq
  from a
)
pivot (max(buyer) for seq in (1 as buyer1, 2 as buyer2, 3 as buyer3));

SQLFiddle here