在以下pivot子句中使用哪个聚合函数?

时间:2017-09-25 10:46:23

标签: database oracle

我有一个表Players,其中包含两列:NameSport_Played。 样本数据如下:

Name.       Sport _played
Ravi            Cricket
Raju            Cricket 
Ronaldo     Football
Messi         Football
Anand        Chess

我希望将具有列的表旋转为运动,并且列应包含按升序排序的玩家的名称。

Cricket         Football         Chess
Raju              Messi            Anand
Ravi              Ronaldo        Null

问题是枢轴需要聚合功能。作为体育专栏的一部分,用于显示玩家姓名的聚合函数。感谢。

1 个答案:

答案 0 :(得分:0)

如果没有您想要输出的示例,很难知道您的意图,但是:

  

将列作为运动玩法,列应包含按升序排序的玩家名称

您无需使用PIVOT,可以使用LISTAGG

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE players ( Name, Sport_played ) AS
SELECT 'Ravi',    'Cricket' FROM DUAL UNION ALL
SELECT 'Raju',    'Cricket' FROM DUAL UNION ALL
SELECT 'Ronaldo', 'Football' FROM DUAL UNION ALL
SELECT 'Messi',   'Football' FROM DUAL UNION ALL
SELECT 'Anand',   'Chess' FROM DUAL;

查询1

SELECT sport_played,
       LISTAGG( name, ',' ) WITHIN GROUP ( ORDER BY name ) As names
FROM   players
GROUP BY sport_played

<强> Results

| SPORT_PLAYED |         NAMES |
|--------------|---------------|
|        Chess |         Anand |
|      Cricket |     Raju,Ravi |
|     Football | Messi,Ronaldo |

<强>更新

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE players ( Name, Sport_played ) AS
SELECT 'Ravi',    'Cricket' FROM DUAL UNION ALL
SELECT 'Raju',    'Cricket' FROM DUAL UNION ALL
SELECT 'Ronaldo', 'Football' FROM DUAL UNION ALL
SELECT 'Messi',   'Football' FROM DUAL UNION ALL
SELECT 'Anand',   'Chess' FROM DUAL;

查询1

SELECT *
FROM   ( SELECT p.*,
                ROW_NUMBER() OVER ( PARTITION BY Sport_played
                                    ORDER BY name ) AS rn
          FROM players p )
PIVOT (
  MAX( Name )
  FOR Sport_Played IN (
    'Cricket' As Cricket,
    'Football' As Football,
    'Chess' AS Chess
  )
)

<强> Results

| RN | CRICKET | FOOTBALL |  CHESS |
|----|---------|----------|--------|
|  1 |    Raju |    Messi |  Anand |
|  2 |    Ravi |  Ronaldo | (null) |

您可以在PIVOT中使用任何(字符串)聚合函数,包括MAX(name)MIN(name)甚至LISTAGG( name, ',' ) WITHIN GROUP ( ORDER BY Name )ROW_NUMBER()解析函数将生成一个唯一的每运动数,因此聚合函数将只对单个值起作用,因此使用哪个聚合函数无关紧要。