5
SQL: Calculate percentage of column
source link: https://proinsias.github.io/til/sql-calculate-percentage-of-column/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
SQL: Calculate percentage of column
less than 1 minute read
# Starting with a table.
> select * from sales;
+-------+------+
| rep | sale |
+-------+------+
| Bob | 15 |
| Sally | 30 |
| Peter | 15 |
+-------+------+
# Use a cross join.
> SELECT Rep, Sale, Sale * 100 / t.s AS `percent of total`
.. FROM sales
.. CROSS JOIN (SELECT SUM(sale) AS s FROM sales) t;
+-------+------+------------------+
| rep | sale | percent of total |
+-------+------+------------------+
| Bob | 15 | 25 |
| Sally | 30 | 50 |
| Peter | 15 | 25 |
+-------+------+------------------+
# Or use a subselect/subsquery.
> SELECT Rep, Sale,
.. Sale * 100 / (SELECT SUM(sale) AS s FROM sales) AS `percent of total`
.. FROM sales;
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK