更改PIVOT函数以添加相应的值而不是SUM

时间:2012-12-21 00:11:01

标签: sql sql-server database sql-server-2008 sql-server-2005

来自此查询:

DECLARE @cols VARCHAR(1000)
DECLARE @sqlquery VARCHAR(2000)

SELECT  @cols = STUFF(( SELECT distinct  ',' + QuoteName(idIndice)
                        FROM tgpwebged.dbo.sistema_Indexacao as a FOR XML PATH('')
                        ), 1, 1, '')      

SET @sqlquery = 'SELECT * FROM
      (      
        select distinct a.id, b.idIndice  
        from tgpwebged.dbo.sistema_Documentos as a  
        join tgpwebged.dbo.sistema_Indexacao as b on a.id = b.idDocumento 
        join tgpwebged.dbo.sistema_DocType as c on a.idDocType = c.id
        join tgpwebged.dbo.sistema_DocType_Index as d on c.id = d.docTypeId 
        where d.docTypeId = 40      
        and (b.idIndice = 11 AND b.valor = ''11111111'' OR b.idIndice = 12 AND b.valor = ''11111'')       
       ) base
       PIVOT 
       (
        Sum(idIndice) 
        FOR [idIndice] IN (' + @cols + ')
        ) AS finalpivot' 

EXECUTE ( @sqlquery )

我得到了这个结果:

id  10      11     12   13      9
13  NULL    11     12   NULL    NULL
14  NULL    11     12   NULL    NULL
16  NULL    NULL   12   NULL    NULL

我没有在pivot中使用Sum(idIndice),而是希望找到一种方法来插入与其对应的值idIndex。

这些值存储在a.value的sabe表中 这是一种简单的方法吗?找不到这个

1 个答案:

答案 0 :(得分:0)

如果每个idIndice都有一个a.value,那么你可以简单地使用MIN(a.value)或MAX(a.value)而不是SUM(idIndice)