Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

sql server - PIVOT on Common Table Expression

I have a CTE as follows

WITH  details
        AS ( SELECT FldId
                   ,Rev
                   ,Words
                   ,row_number() OVER ( PARTITION BY FldId ORDER BY Rev DESC ) AS rn
             FROM   WorkItemLongTexts
             WHERE  ID = 2855
           )
  SELECT  f.ReferenceName
         ,d.FldId
         ,Rev
         ,Words
  FROM    details AS d
          INNER JOIN Fields AS f ON f.FldId = d.FldId
  WHERE   d.rn = 1 ;

The above returns the following output

ReferenceName    |   FldId      |    Rev     |    Words
Description            52            2            Description here  
Objectives           10257           2            Objectives here  
Specification        10258           6            Specification here  
Requirements          10259           6            Requirements here  

I want to apply PIVOT (or whatever is the best option) so that i can get output as follows

Description         |     Objectives     |   Specification      |  Requirements  

Description here        Objectives here         Specification here         Requirements here

Pls. suggest.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You do this:

SELECT
    FldId,
    [Description],
    [Objectives],
    [Specification],
    [Requirements]
FROM (
    SELECT
        ReferenceName,
        FldId,
        REV,
        Words
    FROM CTE
    WHERE RowNumber = 1
) t
PIVOT (
    MIN(Words)
    FOR ReferenceName IN ([Description], [Objectives], [Specification], [Requirements])
) PIV

Or you can add it to your CTE, like this:

;WITH CTE2 AS (
    SELECT
        FldId,
        REV,
        [Description],
        [Objectives],
        [Specification],
        [Requirements],
        ROW_NUMBER() OVER (PARTITION BY FldId ORDER BY REV DESC) AS RowNumber
    FROM TBL
PIVOT (
        MIN(Words)
        FOR ReferenceName IN ([Description], [Objectives], [Specification], [Requirements])
    ) PIV
)

SELECT
    FldId,
    REV,
    [Description],
    [Objectives],
    [Specification],
    [Requirements]
FROM CTE2
WHERE RowNumber = 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...