从特定值转置SQL

时间:2018-02-26 16:18:12

标签: sql sql-server

I have the following table

This is my desire result

这是我的疑问:

SELECT 

DOC_DATA.doc_id AS "doc_id",
DOC_DATA.data_value + '  -  ' + DOC_DATA_1.data_value AS "data_value",
DOC_DATA.stamp_date AS "stamp_date",
DOC_DATA.stamp_uid AS "stamp_uid"

FROM 

P2P.dbo.doc_data DOC_DATA,  
P2P.dbo.doc_data DOC_DATA_1 

WHERE 

DOC_DATA.doc_id = DOC_DATA_1.doc_id
AND ( DOC_DATA.data_index = 64
AND DOC_DATA_1.data_index = 65) 

ORDER BY 

1

但是我只持有“doc_id”,其值为64和65,我实际上想要所有“doc_Id”包括那些没有64和65值的

1 个答案:

答案 0 :(得分:0)

我认为你只想要条件聚合:

select dd.doc_id,
       max(case when dd.data_index = 64 then data_value end) as de_code,
       max(case when dd.data_index = 65 then data_value end) as de_description
from P2P.dbo.doc_data dd
group by dd.doc_id;