将SUM添加到SQL Server查询结果

时间:2015-12-08 21:51:04

标签: sql-server-2014

我需要在SQL Server查询结果的底部添加SUM函数。

这是我的问题:

SELECT 
    STATE, COUNTY, NAME, STNAME, CENSUS2010POP, ESTIMATESBASE2010
FROM 
    [CensusData].[dbo].[SUB-EST2014_ALL]
WHERE 
    (SUMLEV = '50') 
    AND (CENSUS2010POP > 100000) 
    AND (CENSUS2010POP < 200000)

在阅读了几篇关于此的帖子和博客后,我将查询更新为以下内容:

SELECT 
    STATE, COUNTY, NAME = ISNULL(NAME, 'Total'), STNAME, 
    CENSUS2010POP = SUM(CENSUS2010POP), ESTIMATESBASE2010
FROM 
    [CensusData].[dbo].[SUB-EST2014_ALL]
WHERE 
    (SUMLEV = '50') 
    AND (CENSUS2010POP > 100000) 
    AND (CENSUS2010POP < 200000)
GROUP BY 
    ROLLUP(NAME)

但是当我尝试运行修改后的查询时出现错误:

  

专栏&#39; CensusData.dbo.SUB-EST2014_ALL.STATE&#39;在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

我从未在SQL Server中使用SUM函数,因此我不确定此错误的含义或修复错误所需的内容。

有人可以查明我的错误并告诉我需要修复它吗?我正在运行SQL Server 2014。

1 个答案:

答案 0 :(得分:0)

即使你可以让汇总工作,也许这是我认为你想要的最简单的解决方法:

SELECT STATE, COUNTY, NAME, STNAME, CENSUS2010POP, ESTIMATESBASE2010, '' AS Aggregated
FROM [CensusData].[dbo].[SUB-EST2014_ALL]
WHERE (SUMLEV = '50') AND (CENSUS2010POP > 100000) AND (CENSUS2010POP < 200000)
UNION ALL
SELECT NULL, NULL, NULL, NULL, SUM(CENSUS2010POP), SUM(ESTIMATESBASE2010), 'Total'
FROM [CensusData].[dbo].[SUB-EST2014_ALL]
WHERE (SUMLEV = '50') AND (CENSUS2010POP > 100000) AND (CENSUS2010POP < 200000)
ORDER BY Aggregated

从技术上讲,额外的行可能不会出现在底部,所以我不得不添加一个额外的列来强制排序。

以下是分组集的方法。由于您似乎只想要总计,我不相信rollup会起作用,除非您将这四个值连接成一个计算列。

SELECT
    STATE, COUNTY, NAME, STNAME,
    sum(CENSUS2010POP) as CENSUS2010POP,
    sum(ESTIMATESBASE2010) as ESTIMATESBASE2010)
FROM [CensusData].[dbo].[SUB-EST2014_ALL]
WHERE (SUMLEV = '50') AND (CENSUS2010POP > 100000) AND (CENSUS2010POP < 200000)
GROUP BY GROUPING SETS ((STATE, COUNTY, NAME, STNAME), ())
ORDER BY GROUPING(STATE)