开发者

Using Subquery in Select statement

开发者 https://www.devze.com 2022-12-18 03:34 出处:网络
I\'ve got a query that outputs the following table: (0) Age <= 19----------76-------0.12 (1) Age 20 – 24--------661------1.06

I've got a query that outputs the following table:

(0) Age <= 19----------76-------0.12 

(1) Age 20 – 24--------661------1.06 

(2) Age 25 – 29-------4060------6.53 

(3) Age 30 – 34-------7231------11.64 

(4) Age 35 – 39-------9281------14.94 

(5) Age 40 – 44-------9539------15.35 

Total ----------------30848 -----49.65

The first column is the name of a particular segment. The second column is the number of开发者_StackOverflow people in that segment.

The third column is the number of people in that segment as a percentage of the entire table. Note that the total is only approx 50% of the entire base.

What I need is another column that is the percentage of the people in the segment as a percentage of only this base. So the formula for the first row would be (76/30848)*100 which would give 76 as a percentage of 30848. The problem is that the number 30848 isn't known until the end of the query using ROLLUP. How would I go about doing this?


I prefer the first query, but your database may not support it.

SELECT
  segment,
  COUNT(*) AS people,
  100 * people / SUM(people) OVER () AS percentage
FROM table1
GROUP BY
  segment;

SELECT
  t1.segment,
  COUNT(*) AS people,
  100 * t1.people / t2.total_people AS percentage
FROM table1 t1
CROSS JOIN (
    SELECT
      COUNT(*) AS total_people
    FROM table1) t2
GROUP BY
  segment;


I'm a bit confused with your answer. Maybe I need to explain the layout a bit better.

This is a query that produces results for anyone in the two groups aged 20-24 and 30-34.

SELECT CONCAT('(',s.code,') ',s.description) as `Segment`, count(`Age`) AS `Records Selected`, 
ROUND((count(`Age`)/(SELECT count(*) FROM mainTable))*100, 2) 
AS `Percentage of Total`
FROM segment_fields s, mainTable c 
WHERE `segment` = 'Age' AND `code` = `Age` AND `c`.`Age` IN ('1', '3') 
GROUP BY `Age` WITH ROLLUP

Sorry that it looks so messy. Essentially I need a new column just after "percentage of total" that will be the same as "percentage of total". But instead of dividing on the whole base it will only divide by the number of records that are a result of this queries ROLLUP.

0

精彩评论

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