Oracle将行转换为多个聚合值的列

时间:2014-03-04 17:48:15

标签: sql oracle

我知道如何使用pivot将行转换为单个聚合值的列。如何为多个聚合值执行此操作?我想要new_orders_count,new_orders_total,updated_orders_count和updated_orders_total。

订单表

  date        type      total 
--------     -------   -------
03/04/14       NEW      111.11  
03/05/14      UPDATE    45.37  

我想要以下格式输出

  Date         new_count    new_total   updated_count  updated_total
--------      ----------   -----------  -------------  -------------
03/04/14           1          111.11           0          0.00
03/05/14           0          0.00             1         45.37

这个输出是否可行,如果有人可以通过示例提供查询,那将非常感谢。我对单个聚合的查询是:

SELECT order_date, new_orders_count, updated_orders_count
FROM(
    select order_date, order_type, count(*) as order_count
    from orders
    group by order_date, order_type
    order by order_date, order_type
)
PIVOT (
    sum(order_count) FOR order_type IN ('NEW' new_orders_count, 'UPDATE' updated_orders_count)
)

1 个答案:

答案 0 :(得分:2)

您可以在PIVOT子句中包含多个聚合,以逗号分隔as the syntax diagram shows。无论如何,只要你想要相同的FORIN条款。

所以你可以指定两个总和:

SELECT order_date, new_count, new_total, updated_count, updated_total
FROM (
    select order_date, order_type,
      count(*) as order_count, sum(total) as total
    from orders
    group by order_date, order_type
    order by order_date, order_type
)
PIVOT (
    SUM(order_count) AS "COUNT", SUM(total) AS "TOTAL"
    FOR order_type IN ('NEW' AS "NEW", 'UPDATE' as "UPDATED")
);

ORDER_DATE  NEW_COUNT  NEW_TOTAL UPDATED_COUNT UPDATED_TOTAL
---------- ---------- ---------- ------------- -------------
05-MAR-14                                    1         45.37 
04-MAR-14           1     111.11                             

SQL Fiddle