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

时间:2018-08-14 21:02:24

标签: mysql sql sqlfiddle

我正在用group by子句摆弄SQL小提琴,并根据临时表“ A”的结果找到百分比。

这是小提琴。

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 个答案:

答案 0 :(得分:1)

  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 |