如何获得百分比?我可以在同一个查询中获得组Sum和总和吗?

时间:2012-12-25 08:25:54

标签: sql

我有一张类似于下面的表格。我需要得到每个地区的百分比,但要获得它,我必须得到总和,因为它并不总是100。

Customer  Region  Quantity
--------  ------  --------
1         East     10
2         West     10
3         South    10
4         South    10
5         South    10
6         South    10
7         South    10
8         North    10
9         North    10
10        North    10

结果应为:

Region  Percent
------  -------
West     10% 
East     10%
South    50%
North    30%

如果我按地区分组,我只能获得该地区的总和,但我需要整个结果的总和。

4 个答案:

答案 0 :(得分:3)

使用子查询值表达式:

SELECT
   Region,
   Percent =
      Sum(Quantity) * 100.0
      / (SELECT Sum(Quantity) FROM dbo.Table)
FROM dbo.Table
GROUP BY Region

-- alternate denominator for SQL Server 2005 and up:
/ Sum(Quantity) OVER () 

答案 1 :(得分:0)

像这样:

SELECT 
  region, 
  COUNT(Quantity) / 
  (SELECT COUNT(*)
   FROM Table1) * 100 AS "ThePercent"
FROM Table1
GROUP BY region;

SQL Fiddle Demo

这会给你:

| REGION | THEPERCENT |
-----------------------
|   East |         10 |
|  North |         30 |
|  South |         50 |
|   West |         10 |

如果需要为每个百分比打印%,则应使用RDBMS串联方式来执行此操作。但是你没有指定你正在使用的RDBMS,所以你必须这样做。

答案 2 :(得分:0)

这将是:

SELECT Region, 
       COUNT(Quantity)*100.0/(SELECT COUNT(*) FROM Your_Table) AS percentage
       FROM Your_Table
WHERE Region IS not null
GROUP BY Region

SQL Fiddle Demo

输出

REGION  PERCENTAGE
--------------------
East    10
North   30
South   50
West    10

答案 3 :(得分:0)

在SQLServer2005 +中使用带聚合函数的OVER子句

SELECT Region, SUM(Quantity) * 100 / SUM(SUM(Quantity)) OVER () AS Perc
FROM your_table
GROUP BY Region

SQLFiddle上的演示