SQL Server 2008 - Pivot on one column, group by an

2019-09-08 20:47发布

I've just started learning SQL and am struggling with transposing a three column table correctly.

Here's my starting point:

questionid | DebriefingQuestionResults | OperationSessionRecordID
------------------------------------------------------------------
32         |        3                  | 8071
34         |        0                  | 8071
36         |        1                  | 8071
32         |        2                  | 8074
34         |        6                  | 8074
36         |        5                  | 8074

And here's what I want to produce:

    OperationSessionRecordID | 32 | 34 | 36
----------------------------------------------
    8071                     | 3  | 0  | 1       
    8074                     | 2  | 6  | 5

There are only three [questionid] values (32, 34, and 36), but about 12000 [OperationSessionRecordID] values. All columns are of the type int not null.

I know I need to unpivot/pivot on [questionid] from my input table and group by [OperationSessionRecordID], but having looked at numerous other questions I'm still very stuck.

Based on this answer I've got this so far, but am not sure how to proceed as I'm working with a single table and therefore don't need the inner join.

SELECT [32], [34], [36]
FROM
(
    SELECT A.questionid, A.DebriefingQuestionResults
    , row_number() over(partition by a.OperationSessionRecordID)
    FROM dbo.TEMPtable AS A
) AS P
PIVOT
(
  min(P.Value)
  for P.questionid in ([32], [34], [36])
) AS PIV;

When I run this it throws this error, so something's obviously wrong with my use of row_number.

Msg 4112, Level 15, State 1, Line 6 The ranking function "row_number" must have an ORDER BY clause.

Any help would be most appreciated!

SB

2条回答
The star\"
2楼-- · 2019-09-08 21:28

Please try:

select 
    * 
From(
        select * From tbl
    )x pivot
    (
        min(DebriefingQuestionResults) for questionid in ([32],[34],[36])
    )piv
查看更多
不美不萌又怎样
3楼-- · 2019-09-08 21:32

That's a very straightforward pivot. Just:

SELECT OperationSessionRecordID, [32],[34],[38]
FROM TEMPtable
  PIVOT (
  min(DebriefingQuestionResults)
  for questionid in ([32], [34], [36])
) AS PIV;

You don't need to do anything special to get the grouping by OperationSessionRecordID - essentially, every column not mentioned in the PIVOT is a grouping column.

查看更多
登录 后发表回答