SQL - 分组后计算百分比 - 只显示一行

SQL - Calculate percentage after Group by - Only one row is shown

我在 SQL fiddle 上摆弄 group by 子句并根据温度 table "A" 结果找到百分比。

这里是 fiddle.

http://sqlfiddle.com/#!9/faf2f/6959

我确实发现有不同的方法可以实现这一点,比如使用 union all 但我的问题是为什么这个查询只返回一行而不是两行。

数据:

TotalCost
230
200
100
1254

查询:

SELECT Category, Cnt , Cnt/sum(Cnt)  as percent from (

SELECT 
  Case When TotalCost < 301 Then '0-300'
  Else ' > 300' End as Category,
  count(*) as cnt
  FROM Cars      
  group by Category       

  ) A
;

预期结果:

Category    Cnt   percent
0-300        3     75
> 300        1     25

实际结果:

Category    Cnt  percent
> 300        1    25
  1. 您可以尝试按 case when 而不是别名进行分组。
  2. 秒你的总计数需要做所有计数,这样你就可以做一个子查询。

看起来像这样。

SELECT Category, Cnt , Cnt/(select count(*) from Cars) * 100  as percent 
from (
  SELECT 
  (Case When TotalCost < 301 Then '0-300'
  Else ' > 300' End) as Category,
  count(*) as cnt
  FROM Cars
  GROUP BY  (Case When TotalCost < 301 Then '0-300'
  Else ' > 300' End)
) A
ORDER BY 3 DESC

或者您可以使用 CROSS JOIN 来计算总数。

SELECT Category, Cnt , Cnt/v.totle * 100  as percent 
from (
  SELECT 
  (Case When TotalCost < 301 Then '0-300'
  Else ' > 300' End) as Category,
  count(*) as cnt
  FROM Cars
  GROUP BY  (Case When TotalCost < 301 Then '0-300'
  Else ' > 300' End)
) A CROSS JOIN (select count(*) totle from Cars) v

sqlfiddle

结果:

| Category | Cnt | percent |
|----------|-----|---------|
|    0-300 |   3 |      75 |
|    > 300 |   1 |      25 |