我正在使用SQL oracle。我在一张桌子上查询了两种类型的物品:
第一次查询:
SELECT SUM(OLI.QUANTITY) AS "SPECIALITY ITEMS ORDERED - SEPT 2019"
FROM ORDER_LINE_ITEM OLI, CUSTOMER_ORDER CO
WHERE CO.ORDER_ID = OLI.ORDER_ID
AND OLI.ORDER_KIND = 'SPL'
AND CO.ORDER_DATE >= TO_DATE('01 SEPTEMBER 2019', 'DD MONTH YYYY')
AND CO.ORDER_DATE <= TO_DATE('30 SEPTEMBER 2019', 'DD MONTH YYYY')输出:
SPECIALITY ITEMS ORDERED - SEPT 2019
------------------------------------
111第二次查询:
SELECT SUM(OLI.QUANTITY) AS "BUILD YOUR OWN ITEMS ORDERED - SEPT 2019"
FROM ORDER_LINE_ITEM OLI, CUSTOMER_ORDER CO
WHERE CO.ORDER_ID = OLI.ORDER_ID
AND OLI.ORDER_KIND = 'BYO'
AND CO.ORDER_DATE >= TO_DATE('01 SEPTEMBER 2019', 'DD MONTH YYYY')
AND CO.ORDER_DATE <= TO_DATE('30 SEPTEMBER 2019', 'DD MONTH YYYY')输出:
BUILD YOUR OWN ITEMS ORDERED - SEPT 2019
----------------------------------------
49我希望显示这两个查询的结果,并将输出作为相邻的两个列反映如下:
SPECIALITY ITEMS ORDERED - SEPT 2019 | BUILD YOUR OWN ITEMS ORDERED - SEPT 2019
------------------------------------ | ----------------------------------------
111 | 49我该怎么做?
发布于 2019-12-02 17:52:04
就像这样:
select sum(case when oli.order_kind = 'SPL' then oli.quantity else 0 end) result_1,
sum(case when oli.order_kind = 'BYO' then oli.quantity else 0 end) result_2
from order_line_item oli, customer_order co
where co.order_id = oli.order_id
and oli.order_kind in ('SPL', 'BYO')
and co.order_date >= to_date('01 SEPTEMBER 2019', 'DD MONTH YYYY')
and co.order_date <= to_date('30 SEPTEMBER 2019', 'DD MONTH YYYY')另一个选项(不是我推荐的)是重复使用查询,如下所示:
select
(select sum(oli.quantity)
from order_line_item oli, customer_order co
where co.order_id = oli.order_id
and oli.order_kind = 'SPL'
and co.order_date >= to_date('01 SEPTEMBER 2019', 'DD MONTH YYYY')
and co.order_date <= to_date('30 SEPTEMBER 2019', 'DD MONTH YYYY')
) result_1,
--
(select sum(oli.quantity)
from order_line_item oli, customer_order co
where co.order_id = oli.order_id
and oli.order_kind = 'BYO'
and co.order_date >= to_date('01 SEPTEMBER 2019', 'DD MONTH YYYY')
and co.order_date <= to_date('30 SEPTEMBER 2019', 'DD MONTH YYYY')
) result_2
from dual;或者,使用CTE:
with
t_first as
(select sum(oli.quantity) result_1
from order_line_item oli, customer_order co
where co.order_id = oli.order_id
and oli.order_kind = 'SPL'
and co.order_date >= to_date('01 SEPTEMBER 2019', 'DD MONTH YYYY')
and co.order_date <= to_date('30 SEPTEMBER 2019', 'DD MONTH YYYY')
),
--
t_second as
(select sum(oli.quantity) result_2
from order_line_item oli, customer_order co
where co.order_id = oli.order_id
and oli.order_kind = 'BYO'
and co.order_date >= to_date('01 SEPTEMBER 2019', 'DD MONTH YYYY')
and co.order_date <= to_date('30 SEPTEMBER 2019', 'DD MONTH YYYY')
)
select a.result_1, b.result_2
from t_first a cross join t_second b;最后,虽然Oracle在使用您使用的联接时工作得很好,但现在建议遵循最新的ANSI语法和显式联接,即
select ...
from order_line_item oli join customer_order co on co.order_id = oli.order_id
where ...https://stackoverflow.com/questions/59144181
复制相似问题