数据透视表未按预期分组结果

时间:2014-12-03 11:48:56

标签: sql sql-server select sql-server-2012 pivot

我正在使用sql server 2012.我有两个表,请参阅下面的

Table 1 (Region_Strat)

STRAT  SALES_P  COMM
EU     Bob      AC
EU     Dave     AC
NA     John     JP
GB     Mike     AC


Table 2 (Sales_Records)

SALES_P   AMT   SHOP
Bob       5     ABC
Bob       10    DEF
Bob       3     GHI
Dave      12    ABC
John      3     DEF
Mike      11    LIK

我有一个名为vw_sales的视图(存储为视图,无法更改),它基本上将Region_Strat表中的STRAT列添加到Sales_Records表中,以便为我提供下表。

SALES_P   AMT   SHOP    STRAT
Bob       5     ABC     EU       
Bob       10    DEF     EU       
Bob       3     GHI     EU       
Dave      12    ABC     EU       
John      3     DEF     NA       
Mike      11    LIK     GB

这一切都很好。接下来我尝试创建了piviot table(它确实运行但没有给我我需要的结果)。我的问题是

 SELECT SHOP, [EU],[NA],[GB] 
 INTO MY_DB.dbo.TEMP
 FROM
 ( SELECT SALES.SHOP, cast(SALES.Amt as bigint) AS SumOfAmt, Region.COMM, Region.STRAT
  FROM MY_DB.dbo.vw_sales AS SALES JOIN MY_DB.dbo.Region_Strat AS Region ON
  SALES.SALES_P = Region.SALES_P
  WHERE Region.COMM in ('AC','JP') ) tbl
 pivot
 ( sum(SumOfAmt) for STRAT IN([EU],[NA],[GB])) pvt order by SHOP

结果我希望看到,

SHOP   EU    NA    GB
ABC    17    null  null     
DEF    10    3     null
GHI    3     null  null
LIK    null  null  11

然而,我看到的结果是商店DEF显示两次如下。

SHOP   EU    NA    GB
DEF    10    null  null     
DEF    null  3     null

如何更改我的查询以便在一行显示DEF?

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT SHOP, [EU],[NA],[GB] INTO MY_DB.dbo.TEMP
 FROM
 ( SELECT SALES.SHOP, cast(SALES.Amt as bigint) AS SumOfAmt, Region.STRAT
    FROM MY_DB.dbo.vw_sales AS SALES 
    JOIN MY_DB.dbo.Region_Strat AS Region ON SALES.SALES_P = Region.SALES_P
    WHERE Region.COMM in ('AC','JP') 
) tbl
 pivot ( sum(SumOfAmt) for STRAT IN([EU],[NA],[GB])) pvt 
 order by SHOP