0

以下是我的数据透视查询。

    Select MID, [1] as AthleteName1st, 
[2] as AthleteName2nd, 
[3] as AthleteName3rdPoint
from(
select MId, AthleteId , Position,
(row_number() over(partition by Position ,R.EventCode,MId  order by Position)) rn
from L_Results R 
where R.EventCode = '040' and R.Season = (select Season from L_SeasonTable) and Position in (1,2,3) 
) src
pivot
(
  max([AthleteId])
  for Position in ([1] ,[2] , [3]) 
) piv

结果我得到:

MID     AthleteName1st  AthleteName2nd  AthleteName3rdPoint
65      14231808        14201894        14202005
122     14238588        14238562        14186000
178     14238588        14231808        14201894
234     14201847        14201894        14367591
346     14201847        14202176        14186000
374     14201847        14202176        14201912
402     14202176        14249856        14201894
402     14201848        NULL            NULL

结果要求为:

MID     AthleteName1st  AthleteName2nd  AthleteName3rdPoint
65      14231808        14201894        14202005
122     14238588        14238562        14186000
178     14238588        14231808        14201894
234     14201847        14201894        14367591
346     14201847        14202176        14186000
374     14201847        14202176        14201912
402     14202176,       14249856        14201894
        14201848

与在数据透视查询中一样,我从 L_Results 表中仅检索第 1、第 2 和第 3 个位置的数据,在 MID '402' 的 L_Results 表中,对于第一个位置,我有 2 条记录,即为什么我在 MID 的结果中获得 2 条记录402'.. 在上述情况下,我需要得到如上所示的结果,MID '402' 只有一条记录。

我非常感谢您的帮助...谢谢

4

1 回答 1

1

rn由于subquery中的列,您将获得多行src,您从不使用此列,但因为它存在于源中,所以它在group by枢轴的隐含中使用。因此,对于 Mid = 2,运动员 14202176 和 14201848 的位置 = 1。

您需要以每个 Mid/Position 组合为一条记录的格式获取数据,并且您可以使用 sql-server 的 XML 扩展将您的运动员 ID 连接到逗号分隔的字符串中来执行此操作。然后,您可以将它们 PIVOT 为所需的格式:

WITH Data AS
(   SELECT  MId, 
            AthleteId, 
            Position
    FROM    L_Results R 
    WHERE   R.EventCode = '040' 
    AND     R.Season = (SELECT Season FROM L_SeasonTable) 
    AND     Position IN (1, 2 ,3) 
), PivotData AS
(   SELECT  t.Mid,
            t.Position,
            Athletes = STUFF((  SELECT  ',' + CAST(AthleteID AS VARCHAR)
                                FROM    Data t2
                                WHERE   t.Mid = t2.Mid
                                AND     t.Position = t2.Position
                                FOR XML PATH(''), TYPE
                            ).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
    FROM    (   SELECT  DISTINCT Mid, Position 
                FROM    Data
            ) t
)
SELECT  MID, 
        AthleteName1st = [1], 
        AthleteName2nd = [2], 
        AthleteName3rdPoint = [3]
FROM    PivotData
        PIVOT 
        (   MAX(Athletes)
            FOR Position IN ([1], [2], [3])
        ) pvt;
于 2013-04-26T11:26:54.447 回答