如何使用 SQL Server 透视多个列

Posted

技术标签:

【中文标题】如何使用 SQL Server 透视多个列【英文标题】:How to PIVOT multiple columns using SQL Server 【发布时间】:2021-11-12 01:52:06 【问题描述】:

我刚刚编写了一个查询(用于 SQL Server),它返回此输出:

VendorId Category FirstSaleDate StoreId
1 Car 1/1/2021 12
1 Clothes 1/2/2021 13
1 Toys 1/3/2021 14
1 Food 1/4/2021 15
1 Others 1/5/2021 15

但我实际上需要以下输出

VendorId Car StoreId_car Clothes StoreId_clothes Toys StoreId_toys Food StoreId_food Others StoreId_others
1 1/1/2021 12 1/2/2021 1/2/2021 1/3/2021 14 1/4/2021 15 1/5/2021 15

我是 SQL Server 的新手,但我发现这可以通过使用两个 PIVOT 来实现。我真的需要你的帮助才能找到正确的语法。

scenario and output

【问题讨论】:

问题仍然模糊。你能格式化你想要的输出吗?以便于理解 那么类别的数量是固定的吗?在线和 *** 中有很多 povits 示例 【参考方案1】:

您只需要旋转两次并组合结果,例如:

-- Setup example data...
drop table if exists #Example;
create table #Example (
  VendorId int,
  Category varchar(10),
  FirstSaleDate date,
  StoreId int
);

insert #Example (VendorId, [Category], FirstSaleDate, StoreId)
values
  (1, 'Car', '2021-01-01', 12),
  (1, 'Clothes', '2021-01-02', 13),
  (1, 'Toys', '2021-01-03', 14),
  (1, 'Food', '2021-01-04', 15),
  (1, 'Others', '2021-01-05', 15);

-- Pivot data...
with FirstSales as (
  select VendorId, Category, FirstSaleDate from #Example
), Stores as (
  select VendorId, 'StoreId_' + Category as Category, StoreId from #Example
)
select
  FirstSales.VendorId,
  Car, StoreId_Car,
  Clothes, StoreId_Clothes,
  Toys, StoreId_Toys,
  Food, StoreId_Food,
  Others, StoreId_Others
from (
  select VendorId, Car, Clothes, Toys, Food, Others
  from FirstSales
  pivot (min(FirstSaleDate) for Category in ([Car], [Clothes], [Toys], [Food], [Others])) as pvt
) as FirstSales
join (
  select VendorId, StoreId_Car, StoreId_Clothes, StoreId_Toys, StoreId_Food, StoreId_Others
  from Stores
  pivot (min(StoreId) for Category in ([StoreId_Car], [StoreId_Clothes], [StoreId_Toys], [StoreId_Food], [StoreId_Others])) as pvt
) as Stores on Stores.VendorId=FirstSales.VendorId;

【讨论】:

我们可以在没有 CTE 的情况下做到这一点吗?只是因为我必须将此查询添加到 MERGE 是的,你可以在没有 CTE 的情况下做到这一点。只需使用 CTE 选择语句将 from FirstSalesfrom Stores 替换为子查询。

以上是关于如何使用 SQL Server 透视多个列的主要内容,如果未能解决你的问题,请参考以下文章