# How to calculate the quantity of each order based on their number?

There is for example this table
``````id | code | qty
1 | 2324 | 2
2 | 2324 | 1
3 | 2324 | 5
4 | 2388 | 1
5 | 6311 | 12``````

We need to calculate the quantity of each product in the order. T e there is a product ID not ID and code. But given the fact that the product it is still the number. Well, to make a descending sort, but that's the easy part
April 3rd 20 at 17:28
April 3rd 20 at 17:30
Solution
``SELECT DISTINCT code, SUM(qty) as count FROM orders GROUP BY code ORDER BY count DESC``

code | count
6311 | 12
2324 | 8
2388 | 1
Strange, but in the sample a single number
``\$model_order = \Yii::\$app->db->createCommand('SELECT DISTINCT `barcode`, SUM(`qty`) as count FROM order_items GROUP BY `barcode` ORDER BY count DESC')->execute();``
- Liliana36 commented on April 3rd 20 at 17:33
@Liliana36,

For queries not returning data, you should use yii\db\Command::execute()
Yii\db\Command::execute() returns the number of rows processed SQL query.

Try ->queryAll();
``\$model_order = \Yii::\$app->db->createCommand('SELECT DISTINCT `barcode`, SUM(`qty`) as count FROM order_items GROUP BY `barcode` ORDER BY count DESC')->queryAll();``
- Addison_Corwin43 commented on April 3rd 20 at 17:36
@Addison_Corwin43, Yes, indeed. Thank you - Liliana36 commented on April 3rd 20 at 17:39

Find more questions by tags Yii