2012-12-21 53 views
0

從這個查詢:更改PIVOT函數添加相應的值,而不是SUM

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 

相反樞軸使用金額(idIndice)我想找到一種方法來插入與它相對應的值idIndex。

這些值存儲在sabe表a.value 這是一個簡單的方法來執行該操作嗎?不容找到這個無處

回答

0

如果每個idIndice單a.value中,那麼你可以簡單地使用MIN(a.value中)或MAX(a.value中),而不是SUM(idIndice)