简体   繁体   中英

How To Merge Data From Two Tables

I have two tables , L1 and L2 and i want to merge data of these two tables, I want to fetch sum of sale as per item_id according to dates ,I want to fetch data from 2012-01-20 to 22-01-2012 ,L1 table is containing data from 2012-01-20 to 2012-01-21 and L2 tables is containing data of 2012-01-22. please help me out.

Table L1

+-----------------+-------+---------
| date            | sale  | item_id |
+-----------------+-------+---------+
|2012-01-20       | 20    |A        | 
|2012-01-20       | 10    |B        |
|2012-01-21       | 20    |A        |
|2012-01-21       | 30    |B        |
|                 |       |         |
+----+-------------+-----------------

Table L2

+-----------------+-------+----------
| date            | sale  | item_id |
+-----------------+-------+---------+
|2012-01-22       | 20    |A        | 
|2012-01-22       | 10    |B        |     
+----+-------------+-----------------

wanted result

+-------+----------
| sale  | item_id |
+-------+---------+
| 60    |A        | 
| 50    |B        |
+------------------

You can do this with a union all before the aggregation:

select item_id, sum(sale) as sale
from ((select date, sale, item_id
       from l1
      ) union all
      (select date, sale, item_id
       from l2
      )
     ) t
group by item_id;

You can add a where clause for the date range you want.

maybe the error refers to the inner tables ... should the query be as follows?:

select item_id, sum(sale) as sale from ((select date, sale, item_id from l1 ) ALIAS1 union all (select date, sale, item_id from l2 ) ALIAS2 ) t group by item_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