Mega Code Archive

 
Categories / MySQL / Join
 

Retrieve the overall summary into another table, then join that with the original table

mysql> mysql> CREATE TABLE mytable     -> (     ->  rec_id          INT UNSIGNED NOT NULL AUTO_INCREMENT,     ->  name            VARCHAR(20) NOT NULL,     ->  trav_date       DATE NOT NULL,     ->  miles           INT NOT NULL,     ->  PRIMARY KEY (rec_id)     -> ); Query OK, 0 rows affected (0.00 sec) mysql> mysql> INSERT INTO mytable (name,trav_date,miles)     ->  VALUES     ->          ('Ben','2010-11-30',152),     ->          ('Suzi','2010-11-29',391),     ->          ('Henry','2010-11-29',300),     ->          ('Henry','2010-11-27',96),     ->          ('Ben','2010-11-29',131),     ->          ('Henry','2010-11-26',115),     ->          ('Suzi','2010-12-02',502),     ->          ('Henry','2010-12-01',197),     ->          ('Ben','2010-12-02',79),     ->          ('Henry','2010-11-30',203)     -> ; Query OK, 10 rows affected (0.00 sec) Records: 10  Duplicates: 0  Warnings: 0 mysql> mysql> drop TEMPORARY TABLE t; Query OK, 0 rows affected (0.00 sec) mysql> mysql> CREATE TEMPORARY TABLE t     -> SELECT SUM(miles) AS total FROM mytable; Query OK, 1 row affected (0.01 sec) Records: 1  Duplicates: 0  Warnings: 0 mysql> mysql> SELECT mytable.name,     -> SUM(mytable.miles) AS 'miles/driver',     -> (SUM(mytable.miles)*100)/t.total AS 'percent of total miles'     -> FROM mytable, t GROUP BY mytable.name; +-------+--------------+------------------------+ | name  | miles/driver | percent of total miles | +-------+--------------+------------------------+ | Ben   |          362 |                16.7128 | | Henry |          911 |                42.0591 | | Suzi  |          893 |                41.2281 | +-------+--------------+------------------------+ 3 rows in set (0.00 sec) mysql> mysql> drop table mytable; Query OK, 0 rows affected (0.00 sec)