1

I have a MYSQL database with some columns and rows. And I want to select some of rows with same value and sum them and then sort them.

for example:

Id    data
1     5
2     12 
4     42
2     2
1     3
1     8
4     2

something like : data : (16 id : 1) , (data : 14 id : 2) , (data : 44 id : 4)

for doing this I tried this code :

$sql = "SELECT id, SUM(data) AS value_sum FROM table GROUP BY id ORDER BY value_sum DESC LIMIT 30";
$result = mysqli_query($conn, $sql);

    $ids = "";
    $datas = "";

    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result))
        {
            $ids .= $row['p_id'] . '^';
            $datas.= $row['value_sum'] . '^';
        }
    }

And it works fine and I can get sum of rows values sorted as value_sum.

But my problem is the ids are not sorted and I want to get sorted ids too but the result is not sorted. I mean in the result i don't know can I get true id for value_sum.

for more explanation I want this result :

(id 4 : 44) , (id 1 : 16) , (id 2 : 14)

How can I do this ?

1
  • You can order by as many columns as you like in an order by so I'm not clear what you mean by ' i don't know can I get true id for value_sum.' Commented Jun 23, 2019 at 11:52

1 Answer 1

1

you could use sum() , group by and order by sum and id

select  id, sum(data) , concat('(id ',id, ':', sum(data) , ')')
from my_table  
group by  id   
order by sum(data) desc, id asc

or

select  id, sum(data) 
from my_table  
group by  id  
order by id asc, sum(data) desc

and if you need on the same rows

select group_concat(my_col) 
from  (
select  id, sum(data) , concat('(id ',id, ':', sum(data) , ')') my_col
from my_table  
group by  id   
order by sum(data) desc, id asc ) t
Sign up to request clarification or add additional context in comments.

5 Comments

I tried this but the ids are not match with value_sums
i mean ids are sorted by rows not with value_sum
your comments are not clear .. update you question add a clear expected result as a tabular result .. (what mean id are sorted by rows not by sum????)
i update that. i mean this part : id asc , only sorts ids by rows index. but what i want is sorted ids with 'sum(data)' result. @scaisEdge
answer update .. based on your sample (id 4 : 44) , (id 1 : 16) , (id 2 : 14)

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.