SQL Server的行列(SQL Server rows to columns)

2019-09-17 14:40发布

我的查询是:

SELECT vendor.id, insurances.id AS ins_id, vendor_insurances.expiry_date
FROM vendor
INNER JOIN vendor_insurances
ON vendor.id=vendor_insurances.vendor_id

和输出:

id    ins_id    expiry_date
================================
28    1         2006-01-01
28    11        2008-01-01

我想将其转换为:

id    1            11
======================================
28    2006-01-01   2008-01-01

谢谢,

Answer 1:

您将需要使用PIVOT和做同样的事情到这一点:

静态透视 - 为将要转动列短短数

select *
from 
(
  SELECT v.id
    , vi.id AS ins_id
    , vi.expiry_date
  FROM vendor v
  INNER JOIN vendor_insurances vi
    ON v.id=vi.vendorId
) x
PIVOT
(
   MIN(expiry_date)
    FOR ins_id IN ([1], [11])
) p

请参阅SQL小提琴的工作演示

或者你可以使用动态透视,如果你有很多的项目PIVOT的:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(vi.id) 
                  FROM vendor v
                  INNER JOIN vendor_insurances vi
                    ON v.id=vi.vendorId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT id, ' + @cols + ' from 
             (
                SELECT v.id
                    , vi.id AS ins_id
                    , vi.expiry_date
                FROM vendor v
                INNER JOIN vendor_insurances vi
                    ON v.id=vi.vendorId
            ) x
            pivot 
            (
                MIN(expiry_date)
                for ins_id in (' + @cols + ')
            ) p '

execute(@query)

这两种会给你同样的结果。



文章来源: SQL Server rows to columns