Transact SQL Query-Pivot-SQL

时间:2011-03-18 20:57:52

标签: sql sql-server tsql pivot

我有一个表MySeekCatTable,其结构为:

       SeekId  CatId

        J       1<= i<=45

在此表中,每个SeekId都有三个CatId。 表MySeekCatTable引用带有外键的两个表:

SeekTable为主键的第一个表SeekId如下:

        SeekId  Name

          1     John

          2     Kelly

CatTable为主键的第二个表CatId如下:

        CatId   Name

          1     Cat1

          2     Cat2

我需要的是,我必须编写一个查询,其格式为其SeekId中的每个CatId三个:

      SeekId      A          B           C

        1         Cat1       Cat2        Cat3

        i         Cati       Catj        Catk

1 个答案:

答案 0 :(得分:1)

;WITH cte
     AS (SELECT SeekId,
                CatId,
                ct.Name,
                ROW_NUMBER() OVER (PARTITION BY SeekId ORDER BY CatId) AS RN
         FROM   MySeekCatTable sk
                JOIN CatTable ct
                  ON sk.CatId = ct.CatId)
SELECT SeekId,
       MAX(CASE WHEN RN = 1 THEN Name END) AS A,
       MAX(CASE WHEN RN = 2 THEN Name END) AS B,
       MAX(CASE WHEN RN = 3 THEN Name END) AS C
FROM   cte
GROUP  BY SeekId