SUM GROUP BY给出不希望的结果

时间:2016-08-30 02:22:51

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

表T1的前12行:

Name    Status  Duration
Todd    Active  60
Todd    Active  60
Todd    Active  60
Todd    Schedu  60
Todd    Schedu  60
Todd    Schedu  120
Todd    Schedu  120
Bran    Active  30
Bran    Active  30
Bran    Active  60
Bran    No Show 120
Bran    No Show 120

如果我运行此查询(或使用不带GROUP BY的DISTINCT):

SELECT Name, Status, Duration 
FROM Table T1
GROUP BY Name,Status,Duration

我明白了:

Name    Status  Duration
Todd    Active  60
Todd    Schedu  60
Todd    Schedu  120
Bran    Active  30
Bran    Active  60
Bran    No Show 120

从上面的结果来看,我希望期望的结果SUM(Duration) GROUPED BY Name, Status

Name    Status  Duration
Todd    Active  60
Todd    Schedu  180
Bran    Active  90
Bran    No Show 120

我尝试此查询以获得所需的结果:

SELECT Name, Status, SUM(Duration)
FROM Table T1
GROUP BY Name,Status

但是我获得了大量的SUM(持续时间) - 它可能会为每组名称和状态添加所有持续时间而不是不同的持续时间。

4 个答案:

答案 0 :(得分:4)

获得所需内容的一种方法是使用子查询:

SELECT Name, Status, SUM(Duration)
FROM (SELECT Name, Status, Duration 
      FROM Table T1
      GROUP BY Name,Status,Duration
     ) NSD
GROUP BY Name, Status;

答案 1 :(得分:4)

您可以在SUM函数中使用Distinct。它会给你预期的结果。

SELECT Name, Status, SUM(DISTINCT Duration)
FROM T1
GROUP BY Name,Status

答案 2 :(得分:1)

你可以使用CTE,

Initialize-Disk : Unspecified Error
Extended information: The device is not ready.
At line:1 char:1
+ Initialize-Disk 7
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified:    (StorageWMI:ROOT/Microsoft/Windows/Storage/MSFT_Disk) [Initialize-Disk], CimException
+ FullyQualifiedErrorId : StorageWMI 2,Initialize-Disk

答案 3 :(得分:0)

使用temp_cte 如 (选择姓名,状态,持续时间 来自dbo.test2 按名称,状态,持续时间分组 ) 从temp_cte中选择tc.name,tc.status,sum(tc.duration)作为tc 按tc.name,tc.status分组 按名称排序