The self-join can be extended to display the number of days elapsed at each date : Self Join « Join « SQL / MySQL

Home
SQL / MySQL
1.Aggregate Functions
2.Backup Load
3.Command MySQL
4.Cursor
5.Data Type
6.Database
7.Date Time
8.Engine
9.Event
10.Flow Control
11.FullText Search
12.Function
13.Geometric
14.I18N
15.Insert Delete Update
16.Join
17.Key
18.Math
19.Procedure Function
20.Regular Expression
21.Select Clause
22.String
23.Table Index
24.Transaction
25.Trigger
26.User Permission
27.View
28.Where Clause
29.XML
SQL / MySQL » Join » Self Join 
The self-join can be extended to display the number of days elapsed at each date
    
mysql>
mysql> CREATE TABLE rainfall
    -> (
    ->  date    DATE NOT NULL,
    ->  precip  FLOAT(10,2NOT NULL
    -> );
Query OK, rows affected (0.00 sec)

mysql> INSERT INTO rainfall (date, precip)
    ->  VALUES
    ->          ('2002-06-01', 1.5),
    ->          ('2002-06-02', 0),
    ->          ('2002-06-03', 0.5),
    ->          ('2002-06-04', 0),
    ->          ('2002-06-05', 1.0)
    -> ;
Query OK, rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql>
mysql> SELECT FROM rainfall;
+------------+--------+
| date       | precip |
+------------+--------+
2002-06-01 |   1.50 |
2002-06-02 |   0.00 |
2002-06-03 |   0.50 |
2002-06-04 |   0.00 |
2002-06-05 |   1.00 |
+------------+--------+
rows in set (0.00 sec)

mysql>
mysql> SELECT t1.date, t1.precip AS 'daily precip',
    -> SUM(t2.precipAS 'cum. precip',
    -> COUNT(t2.precipAS days,
    -> AVG(t2.precipAS 'avg. precip'
    -> FROM rainfall AS t1, rainfall AS t2
    -> WHERE t1.date >= t2.date
    -> GROUP BY t1.date;
+------------+--------------+-------------+------+-------------+
| date       | daily precip | cum. precip | days | avg. precip |
+------------+--------------+-------------+------+-------------+
2002-06-01 |         1.50 |        1.50 |    |    1.500000 |
2002-06-02 |         0.00 |        1.50 |    |    0.750000 |
2002-06-03 |         0.50 |        2.00 |    |    0.666667 |
2002-06-04 |         0.00 |        2.00 |    |    0.500000 |
2002-06-05 |         1.00 |        3.00 |    |    0.600000 |
+------------+--------------+-------------+------+-------------+
rows in set (0.00 sec)

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

   
    
    
    
  
Related examples in the same category
1.Determine which senders sent themselves a message is to use a self-join
2.To calculate cumulative distance in kilometers at each stage, use a self-join
3.Eliminating Duplicates from a Self-Join Result
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.