OrderDetailID OrderID ProductID Quantity
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
我想总结每个OrderID的所有数量,之后我需要总计所有数量。 我能够创建不同的查询
SELECT OrderID, SUM(Quantity) over ()AS TotalItemsOrdered
FROM OrderDetails
where OrderID in ('10248','10249')
group by OrderID;
和
SELECT SUM(Quantity) over ()AS TotalItemsOrdered
FROM OrderDetails
where OrderID in ('10248','10249');
但我想加入两个查询以显示相同的结果。请教我如何加入查询和显示相同的结果。 谢谢
答案 0 :(得分:2)
我想你想要这个:
SELECT OrderID, SUM(Quantity) as OrderQuantity,
SUM(SUM(Quantity)) OVER () as TotalItemsOrdered
FROM OrderDetails
WHEER OrderID in ('10248','10249')
GROUP BY OrderID;
答案 1 :(得分:0)
不确定为什么你会想要这种格式...通常的方式是按组分组,然后总计是GROUP BY ROLLUP
- 这应该存在于大多数数据库产品中。
使用以下Oracle语法:
with inputs ( OrderDetailID, OrderID, ProductID, Quantity ) as (
select 1, 10248, 11, 12 from dual union all
select 2, 10248, 42, 10 from dual union all
select 3, 10248, 72, 5 from dual union all
select 4, 10249, 14, 9 from dual union all
select 5, 10249, 51, 40 from dual
)
-- end of test data; SQL query begins below this line
select case grouping_id(orderid) when 1 then 'TOTAL'
else to_char(orderid) end as orderid,
sum(quantity) as total_quantity
from inputs
where orderid in (10248, 10249) -- assuming orderid is NUMBER, not VARCHAR
group by rollup (orderid)
order by orderid
;
ORDERID TOTAL_QUANTITY
------- --------------
10248 27
10249 49
TOTAL 76