To determine how many drivers were on the road and how many miles were driven each day : SUM « Aggregate Functions « SQL / MySQL






To determine how many drivers were on the road and how many miles were driven each day

      
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> SELECT trav_date,
    -> COUNT(*) AS 'number of drivers', SUM(miles) As 'miles logged'
    -> FROM mytable GROUP BY trav_date;
+------------+-------------------+--------------+
| trav_date  | number of drivers | miles logged |
+------------+-------------------+--------------+
| 2010-11-26 |                 1 |          115 |
| 2010-11-27 |                 1 |           96 |
| 2010-11-29 |                 3 |          822 |
| 2010-11-30 |                 2 |          355 |
| 2010-12-01 |                 1 |          197 |
| 2010-12-02 |                 2 |          581 |
+------------+-------------------+--------------+
6 rows in set (0.00 sec)

mysql>
mysql>
mysql> drop table mytable;
Query OK, 0 rows affected (0.00 sec)

mysql>

   
    
    
    
    
    
  








Related examples in the same category

1.SUM() function returns the sum of the expression.
2.SUM() the commission
3.Sum by group
4.Some aggregate functions can still produce NULL as a result.
5.What is the total amount of mail traffic and the average size of each message?
6.What is the total population of the United States?
7.Summaries and NULL Values
8.Finding Smallest or Largest Summary Values
9.The number of votes for each programming language is determined with SUM(IF(...))
10.To compute the runner's average speed at the end of each stage