将一行除以整列总和

时间:2014-02-12 16:21:15

标签: sql sql-server tsql

我需要将单行值(在我的情况下为单位)除以整个行总和得到百分比(单位列)。有人可以帮我弄这个吗?下面是代码的代码和数据结果。

    select db.ManufAbbrName Manufacturer, 
       db.ProdName ProductName,
       sum(wk.Units) Units,
       wk.RecordDate RecordDate
  from MDDB db
  join wkdata wk 
    on db.NDC = wk.NDC11 
  join @NDCs nd
    on nd.NDCs = wk.NDC11
 where wk.RecordDate between @StartDate and @EndDate
group by db.ManufAbbrName,
         db.ProdName,
         wk.RecordDate

结果集:

Example1    CLOBETASOL PROPIONATE EMO   264475  2013-11-01 00:00:00.000
Example2    CLOBETASOL PROPIONATE       187371  2013-11-01 00:00:00.000
Example3    OLUX-E                      82154   2013-11-01 00:00:00.000

因此,我需要为第1行中的每个制造商获取第3列的百分比值。因此对于第一个,264475/534000

2 个答案:

答案 0 :(得分:1)

查看OVER子句。 Here是关于它的文章

一个小例子

DECLARE @t TABLE (group_id CHAR(1), value INT)

INSERT INTO @t (group_id, value)
VALUES ('A', 5),('A', 5), ('A', 5),('B', 5),('B', 5)

SELECT group_id, value, group_total, rate = CASE WHEN group_total = 0 THEN 0 ELSE (1.0*value) / (1.0*group_total) END
FROM (
    SELECT group_id, value, group_total = SUM(value) OVER(PARTITION BY group_id)
    FROM @t
) t

答案 1 :(得分:0)

您正在寻找的是SUM(y) OVER(Partition By x)用法。 您可以执行以下操作:

SELECT group_id
, value
, SUM(value) OVER(PARTITION BY group_id)
, CASE WHEN SUM(value) OVER(PARTITION BY group_id) = 0 THEN 0 
ELSE (1.0*value) / (1.0*SUM(value) OVER(PARTITION BY group_id)) END as Rate

FROM t

** SQLFiddle code