Transact SQL Query-Pivot-SQL

2019-07-25 07:57发布

问题:

I have a table MySeekCatTable with a structure:

       SeekId  CatId

        J       1<= i<=45

in this table every SeekId has three CatId. The table MySeekCatTable references two table with foreign keys:

the first table SeekTable with SeekId as primary key is like:

        SeekId  Name

          1     John

          2     Kelly

the second table CatTable with CatId as primary key is like:

        CatId   Name

          1     Cat1

          2     Cat2

My need is that I have to write a query that gives for every SeekId three of its CatId in the format:

      SeekId      A          B           C

        1         Cat1       Cat2        Cat3

        i         Cati       Catj        Catk

回答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