我有两个表, L1和L2 ,我想合并这两个表的数据,我想根据item_id获取销售总额到日期,我想从 2012-01-20到22-01-2012 获取数据,L1表包含2012-01-20到2012-01-21的数据和L2表包含2012-01-22的数据。请帮帮我。
表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 |
+------------------
答案 0 :(得分:5)
您可以在汇总前使用union all
执行此操作:
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;
您可以为所需的日期范围添加where
子句。
答案 1 :(得分:0)
也许错误是指内部表...如果查询如下?:
选择item_id,sum(sale)作为促销 from((选择日期,销售,item_id 来自l1 )ALIAS1联合所有 (选择日期,销售,item_id 来自l2 )ALIAS2 )t group by item_id;