#travel expense = select sum(val) from expenses where type = 'travel';
#food expense = select sum(val) from expenses where type = 'food';
#phone expense = select sum(val) from expenses where type = 'phone';
#total expense = select sum(val) from expenses;
如何在一个查询中找到每笔费用的百分比?假设1000美元的总费用,其中50%用于食品,30%用于旅行,其余用于电话?
travel expense = (select sum(val) from expenses where type = 'travel')/(select sum(val) from expenses)*100 ==> What is the equivalent of this query in one query rather than two?
答案 0 :(得分:1)
无法在“单个”查询中真正执行此操作,因为您需要每行和聚合数据来执行此操作,但是对于某些子查询,它将起作用:
SELECT ((
SELECT SUM(val) FROM expenses WHERE type='travel'
) / (
SELECT SUM(val) FROM expenses
)) AS pct
答案 1 :(得分:1)
试试这个:
select type, sum(val) / (select sum(val) from expenses) * 100 Percentage
from expenses
group by type
结果:
+--------+------------+
| TYPE | PERCENTAGE |
+--------+------------+
| food | 17.7778 |
| other | 20 |
| phone | 35.5556 |
| travel | 26.6667 |
+--------+------------+
这假设您需要表中所有费用的百分比。如果您想要过滤掉其他一些费用,请运行:
select type, sum(val) /
(select sum(val) from expenses
where type in ('travel', 'phone', 'food')) * 100 Percentage
from expenses
where type in ('travel', 'phone', 'food')
group by type
+--------+------------+
| TYPE | PERCENTAGE |
+--------+------------+
| food | 22.2222 |
| phone | 44.4444 |
| travel | 33.3333 |
+--------+------------+
答案 2 :(得分:0)
你能做到:
SELECT type, COUNT(*) FROM expenses GROUP BY type WITH ROLLUP;
......然后从那里把它拉到一起?它确实提供了单个查询中所需的所有数据,即使您必须在查询之外做一些工作。
答案 3 :(得分:0)
select
PreAggregate.TotalExpenses,
PreAggregate.TotalTravel,
PreAggregate.TotalTravel / PreAggregate.TotalExpenses as PctForTravel,
PreAggregate.TotalFood,
PreAggregate.TotalFood / PreAggregate.TotalExpenses as PctForFood,
PreAggregate.TotalPhone,
PreAggregate.TotalPhone / PreAggregate.TotalExpenses as PctForPhone,
PreAggregate.TotalExpenses,
PreAggregate.ExpenseItems
from
( select
sum( if( type = 'travel', val, 0 )) as TotalTravel,
sum( if( type = 'food', val, 0 )) as TotalFood,
sum( if( type = 'phone', val, 0 )) as TotalPhone,
sum( val ) as TotalExpenses,
count(*) as ExpenseItems
from
expenses
where
type in ( 'travel', 'food', 'phone' ) ) PreAggregate