2017-09-26 218 views
0

我不理解,爲什麼我越來越0.01%而不是100%,請告知如何計算MYSQL中的百分比?

這是我的查詢:

SELECT Total_Price,concat(round(total_price/(SUM(total_price)*100),2),'%') AS percentage 
FROM Sales 
WHERE Department IN ('SPORT','MUSIC') 
AND DATE BETWEEN '2016-01-01' AND '2016-03-30' 

感謝

+2

您的查詢沒有意義。你有一個聚合,但沒有「group by」。 –

+0

@GordonLinoff MySQL對於聚合非常寬容。你可以用MySQL做很多錯誤的查詢,它仍然可以工作。看看這個小提琴:http://sqlfiddle.com/#!9/531d0e/2 – Genu

+0

@Genu如果你有一個吸蛋的示範,也是有用的。 – Strawberry

回答

0

嘗試總做一個子查詢.. 。

select t1.total_price, (t1.total_price/t2.grand_total)*100 as pc 
from MyTable t1 
inner join 
(
select sum(tx.total_price) as grand_total 
from MyTable tx 
AND tx.DATE BETWEEN '2016-01-01' AND '2016-03-30' 
) t2 
on 1=1 
WHERE Department IN ('SPORT','MUSIC') 
AND DATE BETWEEN '2016-01-01' AND '2016-03-30' 
+0

謝謝。我收到這樣的錯誤:「你的SQL語法有錯誤;查看與你的MySQL服務器版本相對應的手冊,以便在'AND tx.DATE BETWEEN'2016-01-01'AND'2016附近使用正確的語法-03-30')t2在1 = 1處我處在第7行。你可以提供建議嗎? – DjangoPy

+0

解決方法:SELECT Total_Price,concat(round(total_price /(SUM(total_price))* 100,2),'%'AS百分比 FROM Sales WHERE Department IN('SPORT','MUSIC') AND日期'2016-01-01'和'2016-03-30'; – DjangoPy