计算组结果并将其与详细信息合并

时间:2018-02-06 07:03:58

标签: sql sql-server group-by sql-server-2014

请考虑此结果(报告):

State       Value1       Value2        Value3
---------------------------------------------
State1        103         23%            3
State2        105         32%            12
State3        150         2%             23
Group1        120         19%            3
===================
State4        200         40%            5
State5        250         2%             12
Group2        225         21%            8
===================
...

我有小组,每组都包含一些状态。不,我想对我的详细信息数据运行查询,并在每个组上运行一些自定义函数,以获取Value1Value3。为简单起见,请考虑AVG函数。

我使用Group By子句来生成状态结果,但我如何将状态组与我的结果合并?

由于

修改1)

这是基本数据,这可能与上述输出不匹配:

Id      StateName      Value1       Value2      Value3
1       State1           1             2          3
2       State2           4             2          2
3       State2           3             3          8
4       State2           3             8          5
...

编辑2)

例如:

State1, State2, State3 Belong to `Group1`
State4, state5 Belong to `Group2`
...

2 个答案:

答案 0 :(得分:1)

我认为你看起来如下,我使用了ROLLUP函数来实现功能。

DECLARE @tblStates AS Table
(
    GroupName VARCHAR(10),
    StateName VARCHAR(50),
    Value1 INT,
    Value2 INT,
    Value3 INT
)   

INSERT INTO @tblStates VALUES('Group1','State1',103,23,3)
INSERT INTO @tblStates VALUES('Group1','State2',105,32,12)
INSERT INTO @tblStates VALUES('Group1','State3',150,2,23)
INSERT INTO @tblStates VALUES('Group2','State3',50,10,8)
INSERT INTO @tblStates VALUES('Group2','State4',80,22,1)
INSERT INTO @tblStates VALUES('Group2','State5',20,18,45)

;WITH T as
(
    SELECT
        GroupName,
        StateName,
        AVG(Value1) AS Value1,
        AVG(Value2) AS Value2,
        MIN(Value3) AS Value3
    FROM @tblStates
    GROUP BY ROLLUP(GroupName,StateName)        
)
SELECT 
    CASE ISNULL(StateName,'') WHEN '' THEN GroupName ELSE StateName END AS StateName,
    Value1,
    Value2,
    Value3      
FROM T  
WHERE 
T.GroupName IS NOT NULL 
ORDER BY GroupName

<强>输出:

enter image description here

答案 1 :(得分:0)

我猜您正在寻找GROUPING SETS。此功能允许您在一个语句中按相同GROUP BY子句中的不同值进行聚合。

所以,我想你需要这样的东西(首先将你的数据添加到它所属的组中):

Id      StateName      Value1       Value2      Value3  Group
1       State1           1             2          3     Group01
2       State2           4             2          2     Group01
3       State2           3             3          8     Group01
4       State4           3             8          5     Group02
...

然后,您将拥有:

SELECT ISNULL([Group],[StateName])
      ,AVG()
FROM ...
GROUP BY GROUPING SETS
(
    ([Group])
   ,([Group], [StateName])
);