如何使用与枢轴合并

时间:2016-11-21 18:53:26

标签: sql oracle pivot coalesce

您好我正在尝试使用与数据透视器的合并,因此我可以用零替换NULLS。这就是我所拥有的:

     SELECT * FROM ( SELECT MovieTitle,AwardResultDesc, COALESCE(COUNT(p.AwardResultID),'0') AS T
     FROM tblMovie t1
            INNER JOIN tblAwardDetail p
              ON p.MovieID = t1.MovieID
            INNER JOIN tblAwardResult c
              ON c.AwardResultID = p.AwardResultID
    GROUP BY MovieTitle, AwardResultDesc,p.AwardResultID)

    PIVOT
    (
        max(T) FOR AwardResultDesc IN ('Won' AS "Won",'Nominated' AS "Nominated")
    ) 
    ORDER BY MovieTitle;

似乎我的Pivot由于某种原因忽略了我的合并,有什么建议吗?

1 个答案:

答案 0 :(得分:1)

本质上,数据透视操作涉及聚合函数,因此无需预先聚合数据,但是,您确实需要确保正在旋转的数据足够完整。这里外部加入tblMovie确保每个电影都返回,无论它是否有任何奖励细节。如果您不想返回既未赢得也未获得提名的电影的计数,则使用内部联接代替外部联接:

WITH dta AS (
 SELECT MovieTitle
      , AwardResultDesc
   FROM tblAwardResult ar
   JOIN tblAwardDetail ad
     ON ad.AwardResultID = ar.AwardResultID
  RIGHT JOIN tblMovie m
     ON m.MovieID = ad.MovieID
)
 SELECT *
   FROM dta
   PIVOT( count(*)
     FOR AwardResultDesc IN( 'Won' AS "Won"
                           , 'Nominated' AS "Nominated" ) )
  ORDER BY MovieTitle;