动态列数据透视表返回多行-SQL Server 2014

时间:2018-11-20 16:07:52

标签: sql sql-server tsql pivot

我正在尝试在动态列上编写PIVOT查询。它可以工作,但是会返回多行。

我的查询是

set @query = 'select PanelID, PanelCode, PanelName, EvaluatorID, PersonID, ApplicationID, ' + @cols + ' from (
select 
distinct p.PanelID, p.PanelCode, p.PanelName, e.EvaluatorID, e.PersonID, ppl.LastName, pApps.ApplicationID, ev.AnswerNumeric

from 
tblpanels p inner join tblEvaluators e on p.PanelID = e.PanelID
inner join tblPeople ppl on ppl.PersonID = e.PersonID
inner join tblPanelApps pApps on pApps.PanelID = p.PanelID
inner join tblEvaluations ev on ev.ApplicationID = pApps.ApplicationID and ev.EvaluatorID = e.EvaluatorID

where 
p.PanelID in (1234, 3656)
)tmp
PIVOT
(
max(AnswerNumeric)
For LastName IN (' + @cols + ')
) As P 
Order By PanelID, ApplicationID'
execute(@query)

输出为

+=========+===========+===========+=============+==========+===============+======+=======+
| PanelID | PanelCode | PanelName | EvaluatorID | PersonID | ApplicationID | John | Carol |
+=========+===========+===========+=============+==========+===============+======+=======+
|    1234 |  12123412 | Panel A   |        3674 |     4834 |        112233 | 6    | NULL  |
+---------+-----------+-----------+-------------+----------+---------------+------+-------+
|    1234 |  12123412 | Panel A   |        3674 |     4834 |        112233 | NULL | 4     |
+---------+-----------+-----------+-------------+----------+---------------+------+-------+

每个ApplicationID仅应为一行。如何为以下输出修复此查询?

+=========+===========+===========+=============+==========+===============+======+=======+
| PanelID | PanelCode | PanelName | EvaluatorID | PersonID | ApplicationID | John | Carol | Total
+=========+===========+===========+=============+==========+===============+======+=======+
|    1234 |  12123412 | Panel A   |        3674 |     4834 |        112233 | 6    | 4     | 10
+---------+-----------+-----------+-------------+----------+---------------+------+-------+

编辑:我还需要在每一行的末尾总得分。

1 个答案:

答案 0 :(得分:0)

我修复了它。 evaluatorID和PersonID引起了问题。我将其从子查询中删除,现在已修复。我还添加了总计列。更新后的查询是

logRecursive(a);