Get rows results sorted by 2 columns with Wordpress $wpdb

1.1k Views Asked by At

I have 'transactions' table:

id user amount currency plan_id
1   1     11     usd      1
2   1     9      usd      2
3   1     10     usd      2
4   2     10     usd      7
5   1     7      eur      3
6   1     5      eur      3
7   1     6      eur      4
8   3     3      usd      8

I would like to get the sum of the amounts sorted by currency and then plan_id per given user: $results[currency][plan_id]

$results['usd'][1] = 11
$results['usd'][2] = 19
$results['eur'][3] = 12
$results['eur'][4] = 6

so far I have:

$query = '
    SELECT plan_id, currency, SUM( amount ) as earnings
    FROM transactions
    WHERE user = 1
    GROUP BY currency, plan_id
';
$results = $wpdb->get_results( $query, OBJECT_K );

But it is returning just rows sorted regularly by plan_id ignoring the sorting by currency:

Array ( [1] => stdClass Object ( [plan_id] => 1 [currency] => usd [earnings] => 11 ) [2] => stdClass Object ( [plan_id] => 2 [currency] => usd [earnings] => 19 ) [3] => stdClass Object ( [plan_id] => 3 [currency] => eur [earnings] => 12 ) [7] => stdClass Object ( [plan_id] => 7 [currency] => eur [earnings] => 6 ) ) 

Is it even possible to do with $wpdb?

Please help. Thanks

1

There are 1 best solutions below

1
cabrerahector On BEST ANSWER

You need to tell MySQL how to sort the results using the ORDER BY clause (missing in your query).

This will yield the results you're looking for:

SELECT `plan_id`, `currency`, SUM( `amount` ) AS `earnings`
FROM `transactions`
WHERE `user` = 1
GROUP BY `currency`, `plan_id`
ORDER BY `currency` DESC, `plan_id` ASC