在现有行中重复列值

时间:2019-04-15 15:30:34

标签: sql sql-server

具有具有以下结构的表:

Rownumber ID     Type             Category Value
1         100   1-Purchase Order  Address  Cedar Rd
2                                 City     Beachwood
3                                 State    Ohio
4                                 Zip      44122
5         200   1-Purchase Order  Address  Rockside Rd
6                                 City     Independence
7                                 State    Ohio
8                                 Zip      44131

我希望能够透视表将“地址”,“城市”,“州”和“邮政编码”值移动到列中。但是要做到这一点,我想我需要为每条记录填充ID和Type。 任何指导表示赞赏。

谢谢

我添加了行号字段,并考虑使用LAG和LEAD,但这没用。

Desired Output
Rownumber  ID       Type            Category     Value
1          100   1-Purchase Order   Address     Cedar Rd
2          100   1-Purchase Order   City     Beachwood
3          100   1-Purchase Order   State    Ohio
4          100   1-Purchase Order   Zip      44122
5          200   1-Purchase Order   Address  Rockside Rd   
6          200   1-Purchase Order   City     Independence
7          200   1-Purchase Order   State    Ohio
8          200   1-Purchase Order   Zip      44131

然后最终

Rownumber  ID   Type              Address      City        State  Zip
1         100  1-Purchase Order  Cedar Rd      Beachwood   Ohio   44122
2         200   1-Purchase Order Rockside Rd  Independence Ohio   44122

2 个答案:

答案 0 :(得分:1)

如果我理解正确,则可以使用累积最大值分配id,然后使用条件聚合:

select row_number() over (order by min(id)) as rownumber,
       new_id as id,
       max(type) as type,
       max(case when category = 'Address' then value end) as address,
       max(case when category = 'City' then value end) as city,
       max(case when category = 'State' then value end) as state,
       max(case when category = 'Zip' then value end) as zip
from (select t.*,
             coalesce(id, max(id) over (order by rownumber)) as new_id
      from t
     ) t
group by new_id;

Here是db <>小提琴。

答案 1 :(得分:0)

您可以使用PIVOT这样的语句来获得预期的结果:

SELECT * FROM
(SELECT RowNumber, ID, Type FROM <Your Table Name>) source
PIVOT
(
    MIN (Value)
    FOR Category in 'Address', 'City', 'State', 'Zip'
) AS pvt

有关更多信息,请参见PIVOT文档:https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017