如何使用 SQL 服务器 PIVOT 多列

How to PIVOT multiple columns using SQL Server

我刚刚编写了一个返回此输出的查询(针对 SQL 服务器):

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 服务器的新手,但我看到这可能通过使用两个 PIVOT 来实现。我真的需要你的帮助来找到正确的语法。

scenario and output

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

-- 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;