4

我的查询是:

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

谢谢,

4

1 回答 1

8

您将需要使用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 Fiddle以获取工作演示

或者,如果您有很多要 PIVOT 的项目,您可以使用 Dynamic 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)

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

于 2012-05-29T20:37:31.250 回答