按组划分的总百分比

时间:2017-11-30 20:32:25

标签: sql-server percentage subtotal

我在MyTable中有三列,我需要计算每组的总数百分比。

代码:

SELECT AppVintage, Strategy, Apps FROM mytable GROUP BY AppVintage,Strategy,Apps

每个日期出现4次,每行有不同的类,然后是每行的应用程序总数。

表格如下所示:

https://i.stack.imgur.com/mfPai.png

示例数据集的代码:

CREATE TABLE mytable(
AppVintage VARCHAR(6) NOT NULL PRIMARY KEY
,Strategy   VARCHAR(28) NOT NULL
,Apps       INTEGER  NOT NULL
);
INSERT INTO mytable(AppVintage,Strategy,Apps) VALUES ('Nov16','300',10197);
INSERT INTO mytable(AppVintage,Strategy,Apps) VALUES ('Nov-16','ORIG',29023);
INSERT INTO mytable(AppVintage,Strategy,Apps) VALUES ('Nov-16','400',7219);
INSERT INTO mytable(AppVintage,Strategy,Apps) VALUES ('Nov-16','500',9452);
INSERT INTO mytable(AppVintage,Strategy,Apps) VALUES ('Dec-16','300',12517);
INSERT INTO mytable(AppVintage,Strategy,Apps) VALUES ('Dec-16','ORIG',37762);
INSERT INTO mytable(AppVintage,Strategy,Apps) VALUES ('Dec-16','400',8992);
INSERT INTO mytable(AppVintage,Strategy,Apps) VALUES ('Dec-16','500',11229);'

我需要的是添加一个列来计算每个appvintage每个策略的应用百分比。

有办法做到这一点吗?提前谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用窗口函数执行此操作(假设SQL Server 2008 +)

SELECT
    AppVintage,
    Strategy,
    Apps,
    Apps/SUM(Apps) OVER (PARTITION BY AppVintage) as Percent_Apps
FROM myTable