0

How do I get grand total for orders made by credit card only from such a table :

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 

what is the best way to describe such select operation if you are to search the Internet for a solution to this problem. suppose I am MySQL.

1
  • Which database system is it? Commented Mar 17, 2014 at 2:15

1 Answer 1

3

You can do this with either join or group by. Here is the join method:

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';

If yo could have more than one total for an order, then you would still want to aggregate:

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
Sign up to request clarification or add additional context in comments.

2 Comments

meta_value's data type is something like varchar so you would have to convert it first.
@Szymon . . . That is true. Many databases will convert strings that look like numbers to numbers in a numeric context. That is a rather lame excuse, because I do think such conversions should be explicit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.