SQL连接来自同一个表

时间:2014-03-17 02:12:58

标签: sql select

如何从这样的表中获得信用卡订单总额:

order_id | meta_name | meta_value
___________________________________
1        | type      | credit
1        | total     | 1030.00
...
2        | type      | check
2        | total     | 930.00
..

3        | type      | credit
3        | total     | 330.00 

如果要在Internet上搜索此问题的解决方案,那么描述此类选择操作的最佳方法是什么。 假设我是MySQL。

1 个答案:

答案 0 :(得分:3)

您可以使用joingroup by执行此操作。这是join方法:

select ttype.order_id, cast(ttotal.meta_value as money)
from table ttype join
     table ttotal
     on ttype.order_id = ttotal.order_id and
        ttype.meta_name = 'type' and
        ttype.meta_value = 'credit' and
        ttotal.meta_name = 'total';

如果total可能有多个order,那么您仍然希望聚合:

select ttype.order_id, sum(cast(ttotal.meta_value as money))
from table ttype join
     table ttotal
     on ttype.order_id = ttotal.order_id and
        ttype.meta_name = 'type' and
        ttype.meta_value = 'credit' and
        ttotal.meta_name = 'total'
group by ttype.order_id