开发者

MySQL: Use aggregate result in further calculation

I'm currently working on writing report generators. For one report I need to do a breakdown by a given characteristic (supplier, logging user, language, etc which for each row includes the name of the characteristic I'm interested in, the num开发者_如何学JAVAber of items that match that characterastic, and the percentage of total items this figure represents. The first two aren't a problem, the third is.

For example, to get a breakdown by language I'd be using a query like this.

SELECT lang_id, 
COUNT(IF(open=TRUE,1,NULL)) AS lang_total
FROM table
GROUP BY lang_id;

This gives me the number of items per language.

I can get the total number of items in the table and store it in a variable simply enough with a plain count.

SELECT @totalOpen:=COUNT(*) FROM table WHERE open = TRUE;

Now I want to add a third column, which is the figure in lang_total divided by the value in @totalOpen multiplied by 100 (in other words, the percentage of all items that fit the criteria). Something along the lines of the following:

This is the bit I'm having trouble with, as because as far as I can tell you can't use aggregate columns in calculations.

SELECT lang_id, 
COUNT(IF(open=true,1,NULL)) AS lang_total
(lang_total/@totalOpen)*100 as lang_percent
FROM table
GROUP BY lang_id;

I'm sure that there must be a way of doing this in MySQL, but I've not been able to track it down. Can anyone help out with this?


I read this question now for the first time. I know that probably it's too late to be useful for you but I would have solved in this way.

select lang_id, 
sum(if(open= true,1,0)) as lang_total,
coalesce(sum(if(open= true,1,null)) / @r,0) as percentage
from table,(select @r:=count(*) from table where open = TRUE) as t
group by lang_id;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜