我正在用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
答案 0 :(得分:1)
case when
而不是别名进行分组。看起来像这样。
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
结果:
| Category | Cnt | percent |
|----------|-----|---------|
| 0-300 | 3 | 75 |
| > 300 | 1 | 25 |