以下是我的原始数据:
raw data

我希望数据如下所示:pivoted data

select cvid, cid,67554,67555,67556,67557
from #temp2 pivot
    (
    max(lcd)
    for qid in ([67554],[67555],[67556],[67557])
    )as P


这是我尝试的代码。需要帮忙!

最佳答案

使用相当通用的语法,这是一种可能:

select CVID, CID, sum(case when QID = 67554 then LCD else 0 end) as [67554],
                  sum(case when QID = 67555 then LCD else 0 end) as [67555],
                  sum(case when QID = 67556 then LCD else 0 end) as [67556],
                  sum(case when QID = 67557 then LCD else 0 end) as [67557]
from test1
group by CVID, CID;


我在SSMS for SQL Server 2012中对此进行了测试。

10-06 06:39