1

我有一个类似于这样的表结构:

    id | order1_id | order1_type | order1_amount | order2_id | order2_type | order2_amount
------------------------------------------------------------------------------------------
    1        1           3             4                 1         4              5
    2        2           1             1                 1         3              2
    3        1           4             4                 2         2              1

我想得到这样的数据:

order_id | 订单类型 | 订单金额

1          3            6
1          4            9
2          1            1
2          2            1

我想按类型分组,并对订单金额求和。我怎样才能做到这一点 ?

谢谢,

4

2 回答 2

3

我将在子查询中使用联合来排列列,然后对其进行分组和求和。

假设您坚持使用这种不太理想的表结构,您可能希望创建一个表示下面子查询的视图,然后针对该视图运行 group by/sum。我猜这样的视图可能在更多的地方有用,而不仅仅是这个查询。

select t.order_id, t.order_type, sum(t.order_amount)
from (select order1_id as order_id, order1_type as order_type, order1_amount as order_amount
      from orders
      union all
      select order2_id as order_id, order2_type as order_type, order2_amount as order_amount
      from orders  
      union all        
      select order3_id as order_id, order3_type as order_type, order3_amount as order_amount
      from orders 
      union all         
      select order4_id as order_id, order4_type as order_type, order4_amount as order_amount
      from orders    
      union all      
      select order5_id as order_id, order5_type as order_type, order5_amount as order_amount
      from orders) t
group by t.order_id, t.order_type
于 2011-01-11T04:24:16.087 回答
2

最简单的方法是使用视图来解开有问题的设计表,然后对视图进行分组和求和。

create view normalized_orders as
select order1_id as order_id, 
    order1_type as order_type,
    order1_amount as order_amount
    from your_table
union all
select order2_id as order_id, 
    order2_type as order_type,
    order2_amount as order_amount
    from your_table

然后你可以这样做:

select order_id, order_type, sum(order_amount) 
from normalized_orders
group by order_id, order_type
order by order_id, order_type
于 2011-01-11T04:36:23.463 回答