SQL Server 2008 - Pivot on one column, group by another, maintain reference to third

StackOverflow https://stackoverflow.com/questions/23240712

  •  08-07-2023
  •  | 
  •  

Вопрос

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

Это было полезно?

Решение

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.

Другие советы

Please try:

select 
    * 
From(
        select * From tbl
    )x pivot
    (
        min(DebriefingQuestionResults) for questionid in ([32],[34],[36])
    )piv
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top