在SQL中创建动态SUM列

时间:2017-08-21 10:43:41

标签: sql sql-server sum

我有以下查询返回,商店编号及其地区,以及2016年商店销售额的总和。

SELECT
EU.[STORE NO]                               
,EU.REGION
,SUM(SA.SALESEXVAT) AS 'STORE SALES'


FROM
[BHXSQL2014-DEV].BManalytics.dbo.EUactivestores EU

INNER JOIN
EUUKSQL01.dashboard.dbo.stocksalesaggregateweek sa 
ON  eu.[Store No]   =    sa.[branchno] 

WHERE
sa.Fiscalyear  =     2016


GROUP BY 
EU.[Store No]   
,EU.REGION  

我如何添加第4列,以总结每家商店所在地区的销售额。

每个地区都有很多商店,因此在同一地区有商店的每个ROW上,这个值都是相同的。

希望我解释一下好吗?

1 个答案:

答案 0 :(得分:4)

您可以使用窗口功能:

SELECT EU.[STORE NO], EU.REGION,
       SUM(SA.SALESEXVAT) AS STORE_SALES
       SUM(SUM(SA.SALESEXVAT)) OVER (PARTITION BY EU.REGION) as REGION_STORE_SALES
FROM [BHXSQL2014-DEV].BManalytics.dbo.EUactivestores EU INNER JOIN
      EUUKSQL01.dashboard.dbo.stocksalesaggregateweek sa 
      ON eu.[Store No] = sa.[branchno] 
WHERE sa.Fiscalyear  =     2016
GROUP BY EU.[Store No], EU.REGION ;