2012-03-22 43 views
0
#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%的旅行,其餘的手機?在一個MySQL查詢中查找結果

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? 

回答

1

真的不能做一個「單」查詢,因爲你需要按行和彙總數據要做到這一點,但也有一些子查詢,它會工作:

SELECT ((
    SELECT SUM(val) FROM expenses WHERE type='travel' 
)/(
    SELECT SUM(val) FROM expenses 
)) AS pct 
0

您可以做:

SELECT type, COUNT(*) FROM expenses GROUP BY type WITH ROLLUP; 

...並從那裏拉起它自己?它確實在單個查詢中提供了所需的所有數據,即使您必須在查詢之外完成一些工作。

+0

不知道ROLLUP。 – ThinkCode 2012-03-22 14:54:35

+0

ROLLUP是萬能的總和 – 2012-03-22 14:55:04

+0

ROLLUP很有趣。但是,如Marc所示,通過一個查詢來完成任務。不知道我是否可以使用ROLLUP進行這個Q. – ThinkCode 2012-03-22 15:01:11

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 
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 | 
+--------+------------+