我有下表。
date | ref# | received_qty | issued_qty | remarks
----------------------------------------------------
2017-07-01 |112 | 5 | 0 | order
2017-07-01 |113 | 3 | 0 | order
2017-07-02 |112 | 0 | 4 | issue
2017-07-02 |112 | 2 | 0 | order
我需要在不同的列中按日期显示类似的数据。
date | ref# | received_qty | issued
--------------------------------------------------------
2017-07-01| 112 | 5 | 0
2017-07-01| 113 | 3 | 0
2017-07-02| 112 | 4 | 2
答案 0 :(得分:0)
您可以将聚合与带有带有union all
的having子句一起使用,以将两个选择语句组合为:
with tab(date, ref, received_qty, issued_qty, remarks) as
(
select '2017-07-01',112,5,0,'order' union all
select '2017-07-01',113,3,0,'order' union all
select '2017-07-02',112,0,4,'issue' union all
select '2017-07-02',112,2,0,'order'
)
select date, ref,
sum(issued_qty) as received_qty,
sum(received_qty) as issued_qty
from tab
group by date, ref
having min(remarks) = 'issue'
union all
select date, ref,
sum(received_qty) as received_qty,
sum(issued_qty) as issued_qty
from tab
group by date, ref
having min(remarks) = 'order'
order by date, ref;
答案 1 :(得分:0)
我怀疑你只是想要这个:
select date, ref, sum(received_qty) as received_qty, sum(issued_qty) as issued_qty
from tab
group by date, ref
order by date, ref;
请注意,这将返回:
date | ref# | received_qty | issued
--------------------------------------------------------
2017-07-01| 112 | 5 | 0
2017-07-01| 113 | 3 | 0
2017-07-02| 112 | 2 | 4
这个结果比您拥有的更具意义。