简体   繁体   中英

Joining table with its self

i have question here...

Table : history
|id   |transaction|created_at         |merchant_id|
|-----|-----------|-------------------|-----------|
|1    |400        |2015-10-12 11:08:37|33         |
|1    |500        |2015-10-15 09:38:22|33         |
|1    |600        |2015-10-21 14:47:12|22         |
|2    |100        |2015-09-26 10:48:27|31         |
|2    |500        |2015-09-30 11:18:07|27         |
|2    |300        |2015-10-02 17:33:57|31         |

i want when im do query:

SELECT SUM(a.transaction)/COUNT(a.transaction) AS avg_trans
FROM history AS a GROUP BY a.id, a.merchant_id

Result:
|id    |avg_trans|merchant_id|
|------|---------|-----------|
|1     |450      |33         |
|1     |600      |22         |
|2     |200      |31         |
|2     |500      |27         |

then show avg_trans into table history, like this :

|id   |transaction|created_at         |avg_trans|merchant_id|
|-----|-----------|-------------------|---------|-----------|
|1    |400        |2015-10-12 11:08:37|450      |33         |
|1    |500        |2015-10-15 09:38:22|450      |33         |
|1    |600        |2015-10-21 14:47:12|600      |22         |
|2    |100        |2015-09-26 10:48:27|200      |31         |
|2    |200        |2015-09-30 11:18:07|500      |27         |
|2    |300        |2015-10-02 17:33:57|200      |31         |

anyone can help me?

Use a correlated subquery:

select h.*,
       (select avg(h2.transaction)
        from history h2
        where h2.id = h.id
       ) as avg_trans
from history h;

You can also do this with a group by . However, the above can take advantage of an index on history(id, transaction) . Also note that SQL has the built-in aggregation function AVG() , so you might as well use it.

The group by / join version looks like:

select h.*, hh.avg_trans
from history h join
     (select id, avg(h2.transaction) as avg_trans
      from history h2
      where h2.id = h.id
     ) hh
     on h.id = hh.id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM