在组内进行Transact SQL计算

时间:2017-07-16 08:46:02

标签: sql-server tsql group-by

我想计算群组内的权重。假设我有一个这样的表和一个组变量,我想计算权重列,它是产品值,超过该组中所有产品值的总和。怎么办呢?

数据示例:

我想从这张桌子开始:

Original Table

到此表:

Table I want to create

这意味着权重列不存在。目标是创建一个包含所有原始列的新表以及一个名为weight的新列。

重量计算示例:对于第5行B组产品x,重量计算为重量= 10/40。

3 个答案:

答案 0 :(得分:1)

您可以使用窗口功能来实现此目的。这是一个例子:

SELECT
    1.0 / (SUM([Value]) OVER (PARTITION BY [Group])) * [Value] AS [Weight]
FROM [YourTable]

我建议您在现有表格的基础上创建一个视图(当然,这取决于您的需求)。您可以像这样创建视图:

CREATE VIEW [YourView] AS
SELECT
    [Group],
    Product,
    [Value],
    CASE 
        WHEN (SUM([Value]) OVER (PARTITION BY [Group])) = 0 THEN 0 
        ELSE 1.0 / (SUM([Value]) OVER (PARTITION BY [Group])) * [Value] END AS [Weight] 
FROM [YourTable]

答案 1 :(得分:0)

SELECT [group], SUM(weight)
FROM table
GROUP BY [group]

在回复您的评论时 - 您可以创建一个视图,当您查询它时会动态计算重量:

CREATE VIEW [dbo].[GroupWeights]
AS
SELECT [group], SUM(weight)
FROM table
GROUP BY [group]

回答您问题中最近的修改:

CREATE VIEW ProductWeights
AS
SELECT [p.group], product, value, (value / (SELECT SUM(value) FROM Products WHERE [group] = [p.group] GROUP BY [group])) AS [weight]
FROM Products AS p

答案 2 :(得分:0)

您可以使用SELECT INTO创建新表,使用分区SUM来按组获取总和,如下所示:

Select [Group], Product, [Value], 
   [Weight] = ([Value]*1.0)/SUM([Value]) over(Partition by [Group])
   INTO NewTable from YourTable