SUM正在减少记录量

时间:2013-03-24 08:14:30

标签: sql sql-server group-by sum aggregate

我正在尝试从两个查询的联合中进行选择 这两个查询的联合让我说90,000记录,但是当我选择它们的总和时,它让我说89,800条记录。因此,总和正在减少记录数量。

Select Site,building,..., 
SUM(PhysicalCount) as PhysicalResult
From(
    Select Site,building,...,
    Count(TagID) as PhysicalCount 
    FROM Physical
    Where <SomeCondition1>
    Union
    Select Site,building,...,
    Count(TagID) as PhysicalCount 
    FROM Physical
    Where <SomeCondition2>
) T1
Group by Site,building,...,

3 个答案:

答案 0 :(得分:2)

是的,您应该看到预期的差异。
举个例子,你会理解为什么在分组后,总行数小于你在内部联合查询中获得的行数。 例如,这是您的内部查询输出:

site1, building1, ...., 15
site1, building1, ....., 16

您在内部查询中使用UNION,但这两行不同,因为count不同。
但是,您在外部查询中使用GROUP BY,逐个站点,构建,.....
然后这两行将变成一行,计数将为31

答案 1 :(得分:2)

这就是你所期望的。

构建这个简单的例子:

CREATE TABLE #X 
(
[Id] VARCHAR(100),
[Amount] INT
)
INSERT INTO #X VALUES
('michaeljackson',10),
('jim',20),
('jill',20),
('j',30)

CREATE TABLE #Y 
(
[Id] VARCHAR(100),
[Amount] INT
)
INSERT INTO #Y VALUES
('michaeljackson',100),
('jim',200),
('jill',200),
('j',300)

现在尝试运行:

SELECT * FROM #X
UNION
SELECT * FROM #Y

现在运行以下脚本,这是您脚本的模型:

SELECT  x.Id,
    SUM(x.Amount) AS "Aggregate"
FROM 
    (
    SELECT * FROM #X
    UNION
    SELECT * FROM #Y
    ) x
GROUP BY x.Id

UNION不会聚合UNION在一起的脚本中的金额 - 它只是将一个记录集附加到另一个记录集上并删除重复项。如果要将一个附加到另一个并保留重复项,请使用UNION ALL

答案 2 :(得分:2)

首先,您的查询没有意义,因为子查询中有count没有对应的group by。这应该会返回错误。

如果您想要组的总和,而不是聚合组,那么请使用窗口函数:

Select Site,building,..., 
       SUM(PhysicalCount) over (partition by site, building) as PhysicalResult
From(
    Select Site,building,...,
    Count(TagID) as PhysicalCount 
    FROM Physical
    Where <SomeCondition1>
    group by site, building
    Union
    Select Site,building,...,
    Count(TagID) as PhysicalCount 
    FROM Physical
    Where <SomeCondition2>
    group by site, building
    ) T1

虽然union删除了重复项,但显然网站和建筑物的组合具有不同的数量。

也许你的意图实际上是这样做的:

    Select Site, building, Count(TagID) as PhysicalCount 
    FROM Physical
    Where (<SomeCondition1>) or (<someCondition2)
    group by site, building;