Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL dividing column by a number in another table

Tags:

sql

I have two tables:

total_table = 
| Title | Value |
|-------|-------|
| total |   20  |

breakdown_table =
|  Title | Value |
|--------|-------|
|  total |   20  | (this is the same as the above table)
| type a |   10  |
| type b |    5  |
| type c |    5  |

I would like to create a new table which includes both columns from breakdown_table but adds a 3rd column that shows the breakdown percentages (100%, 50%, 25%, 25%). How can I do this without hardcoding the denominator?

Here's some syntax I've tried but it keeps giving me errors about commas and equijoin. I'm not trying to join the tables with a key, I just want to use the single value in the total_table.

data_out = SELECT breakdown_table.*,
                  breakdown_table.Value / total.Value
           FROM breakdown_table, total_table;
like image 925
wheeeee Avatar asked Sep 03 '25 14:09

wheeeee


1 Answers

You can cross join the tables (properly):

SELECT 
  b.*, 
  100.0 * b.Value / t.Value as data_out
FROM breakdown as b cross join total as t;
like image 109
forpas Avatar answered Sep 05 '25 02:09

forpas