小编典典

SQL Server行到列

sql

我的查询是:

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

谢谢,


阅读 185

收藏
2021-05-23

共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

或者,如果您有很多要发送到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)

两者都会给您相同的结果。

2021-05-23