通过PIVOT查找最高总数?

时间:2014-05-29 16:43:56

标签: sql sql-server pivot

我有一个大型数据集,我需要计算"是"每个问题的回答。我的查询如下:

SELECT 
SUM(CASE (question1) WHEN 'Y' THEN 1 ELSE 0 END) as question1
, SUM(CASE (question2) WHEN 'Y' THEN 1 ELSE 0 END) as question2
, SUM(CASE (question3) WHEN 'Y' THEN 1 ELSE 0 END) as question3
, SUM(CASE (question4) WHEN 'Y' THEN 1 ELSE 0 END) as question4
, SUM(CASE (question5) WHEN 'Y' THEN 1 ELSE 0 END) as question5
...... ( + dozens more ) ...
FROM myTable

这给了我一张这样的表格:

question1 | question2 | question3 | question4 | question5 | ...
-------------------------------------------------------------------
346       | 187       | 240       | 256       | 261       | ...

精细。但是我需要在这一行中找到最高的3个值。我已经研究了PIVOT函数,试图将我的表转换成如下所示:

name      | value
--------------------
question1 | 346
question2 | 187 
question3 | 240
question4 | 256
question5 | 261

但我坦率地不明白示例代码的FOR ... IN部分是如何工作的,而且我应该如何列出一个列"其中包含将成为的值列标题",如文档所述:

PIVOT
(
    <aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
    IN ( [first pivoted column], [second pivoted column],
    ... [last pivoted column])
) AS <alias for the pivot table>

由于我的表只有一行,因此我没有列成为列标题。任何人都可以帮助我理解如何使用我的1行数据集 - 或者更好的是,采用不同的方法来解决这个问题?我觉得我可能会错过更简单的东西。同样,最终目标是找到总数最高的3个问题。

2 个答案:

答案 0 :(得分:2)

您不需要PIVOT,如果您想获得这些结果,则需要使用UNPIVOT。还有其他方法可以执行此操作,例如,您可以使用CROSS APPLY

;WITH CTE AS
(
SELECT  SUM(CASE (question1) WHEN 'Y' THEN 1 ELSE 0 END) as question1
        , SUM(CASE (question2) WHEN 'Y' THEN 1 ELSE 0 END) as question2
        , SUM(CASE (question3) WHEN 'Y' THEN 1 ELSE 0 END) as question3
        , SUM(CASE (question4) WHEN 'Y' THEN 1 ELSE 0 END) as question4
        , SUM(CASE (question5) WHEN 'Y' THEN 1 ELSE 0 END) as question5
        ...... ( + dozens more ) ...
FROM myTable
)
SELECT x.[name], x.Value
FROM CTE t
CROSS APPLY 
(
    VALUES
        ('question1', t.question1),
        ('question2', t.question2),
        ....
        ('questionN', t.questionN)
) x ([name], Value);

答案 1 :(得分:0)

我想这可以帮到你:

CREATE TABLE #X(ID INT IDENTITY,question1 INT,question2 INT,question3 INT ,question4 INT ,question5 INT)


INSERT INTO #X
select 346,187,240,256,261  


select top 3 *
from (
select 
id,
question,
[value]
from #X
unpivot([value]  for question in(question1,question2,question3,question4,question5))P
)X 
order by [value] desc