如何将 table 转换为 SQL 中的另一个(类似于 pivot,但不完全)

how to convert a table to another in SQL (similar to pivot, but not exactly)

我有一个数据库 table 在 SQL Server 2016 中如下所示:

   ProjectKey  -   Type    -    Percentage
   ----------------------------------------
   40               8            100%
   50               6            40%
   50               9            60%
   60               3            30%
   60               8            30%
   60               9            40%

(同一 ProjectKey 的最大行数为 3)

我想编写一个查询,以便能够将上面的 table 转换为以下内容:

   ProjectKey   - Type1  -  Percentage1  - Type2  - Percentage2  - Type3  - Percentage3
   -------------------------------------------------------------------------------------
   40              8         100%           null     null           null    null
   50              6         40%            9        60%            null    null
   60              3         30%            8        30%            9       40%

如果可以通过编写 SQL 查询来实现,那就太好了。任何人都可以帮忙吗?非常感谢!

您可以使用 row_number() 和条件聚合:

select projectkey,
       max(case when seqnum = 1 then type end) as type_1,
       max(case when seqnum = 1 then percentage end) as percentage_1,
       max(case when seqnum = 2 then type end) as type_2,
       max(case when seqnum = 2 then percentage end) as percentage_2,
       max(case when seqnum = 3 then type end) as type_3,
       max(case when seqnum = 3 then percentage end) as percentage_3
from (select t.*,
             row_number() over (partition by projectkey order by type) as seqnum
      from t
     ) t
group by projectkey;