基于总计计算坡度

时间:2018-11-06 05:20:36

标签: sql-server

我目前在下面的查询中可以按城市(不包括伦敦)查看销售情况。

SELECT
City, 
SUM(Sales) as Total
FROM Employees
WHERE City != 'London'
Group BY City

当前输出

City            Total    
Kirkland          3         
Redmond           4         
Seattle           9        
Tacoma            2

我需要在下面创建第三列“百分比”(%,无小数点)。你能帮我这个忙吗?提前非常感谢您!

所需的输出

City            Total    Percentage
Kirkland          3         17%
Redmond           4         22%
Seattle           9         50%
Tacoma            2         11%

2 个答案:

答案 0 :(得分:4)

请尝试以下查询。

SELECT
City, 
SUM(Sales) as Total
FROM Employees
WHERE City != 'London'
Group BY City

The result will be;
   City            Total
   Kirkland          3
   Redmond           4
   Seattle           9
   Tacoma            2

要计算百分比,

DECLARE @Total INT
SELECT @Total=SUM(Sales) FROM Employees WHERE City != 'London'

SELECT
 City, 
 SUM(Sales) as Total,
 CAST(SUM(Sales) * 100 / CAST(@Total AS DECIMAL(18,2)) AS DECIMAL (18,2))
FROM Employees
WHERE City != 'London'
Group BY City

答案 1 :(得分:1)

ELSE部分更改为0

SELECT
City, 
SUM(CASE WHEN City <> 'London' THEN Sales ELSE 0 END) as Total
FROM Employees
Group BY City

或者为什么不排除值为City的{​​{1}}

London