简单的数据透视表

时间:2014-08-22 17:43:44

标签: sql sql-server tsql

我有两个表:Interfaces和ConnectionStrings。表之间存在多对多关系,我通过添加名为InterfaceConnectionStrings的第3个表对其进行了规范化。我可以通过存储过程按如下方式查询表,以获取我需要的数据:

Select I.InterfaceName as IName
,CS.ConnectionStringDescription as Descr
,CS.ConnectionStringValue as Value
from ConnectionStrings CS
JOIN InterfaceConnectionStrings ICS
on CS.ConnectionStringDescription = ICS.ConnectionStringDescription
JOIN Interfaces I
on ICS.InterfaceName = I.InterfaceName
where InterfaceName = @InterfaceName

结果如下所示:

**IName**       **Descr**     **Value**
InterfaceX      CSDescr1      CS1Value
InterfaceX      CSDescr2      CS2Value
InterfaceX      CSDescr3      CS3Value

我想找到一个返回以下内容的查询:

**IName**       **CSDescr1**     **CSDescr2**  **CSDescr3**
InterfaceX      CS1Value         CS2Value      CS3Value   

我尝试使用PIVOT,但没有取得多大进展。以下是我到目前为止的情况:

Select InterfaceName as IName
,ConnectionStringDescription as Descr
,ConnectionStringValue as Value
From (
Select I.InterfaceName 
,CS.ConnectionStringDescription
,CS.ConnectionStringValue
 from ConnectionStrings CS
JOIN InterfaceConnectionStrings ICS
on CS.ConnectionStringDescription = ICS.ConnectionStringDescription
JOIN Interfaces I
on ICS.InterfaceName = I.InterfaceName) PvtBase

PIVOT

( MAX(PvtBase.Value) FOR
PvtBase.Descr IN PvtBase.Value) as Pvt

2 个答案:

答案 0 :(得分:1)

例如:

declare @table table (iName varchar(25), Descr varchar(25), Value varchar(25))

insert into @table
select 'InterfaceX','CSDescr1','CS1Value' UNION ALL
select 'InterfaceX','CSDescr2','CS2Value' UNION ALL
select 'InterfaceX','CSDescr3','CS3Value'

select *
from (select * from @table) sub
pivot (max(value) for descr in ([CSDescr1],[CSDescr2],[CSDescr3])) p

对于您,只需将SELECT * FROM @TABLE替换为您的初始查询(添加一些别名)。

select *
from ( Select I.InterfaceName as iName
             ,CS.ConnectionStringDescription as descr
             ,CS.ConnectionStringValue as value
             from ConnectionStrings CS 
             JOIN InterfaceConnectionStrings ICS
                on CS.ConnectionStringDescription = ICS.ConnectionStringDescription
             JOIN Interfaces I
                on ICS.InterfaceName = I.InterfaceName
             where InterfaceName = @InterfaceName) sub
pivot (max(value) for descr in ([CSDescr1],[CSDescr2],[CSDescr3])) p

答案 1 :(得分:1)

SELECT *
FROM (
        Select  I.InterfaceName                 as IName
               ,CS.ConnectionStringDescription  as Descr
               ,CS.ConnectionStringValue        as Value
        from ConnectionStrings CS
        JOIN InterfaceConnectionStrings ICS
        on CS.ConnectionStringDescription = ICS.ConnectionStringDescription
        JOIN Interfaces I
        on ICS.InterfaceName = I.InterfaceName
        where InterfaceName = @InterfaceName
     ) t
PIVOT (MAX(Value)
       FOR Descr
       IN ([CSDescr1],[CSDescr2],[CSDescr3])
      )p