vendredi 2 février 2018

How to group database records by field using another field for calculating aggregate values in Laravel?

I have a table with fields 'name', 'type' and 'amount', for example

|------------|-------|----------|
| name       | type  | amount   |
|------------|-------|----------|
| Name_1     | 1     | 100      |
|------------|-------|----------|
| Name_1     | 2     | 200      |
|------------|-------|----------|
| Name_2     | 1     | 300      |
|------------|-------|----------|
| Name_1     | 1     | 400      |
|------------|-------|----------|

And I need to receive a result

|------------|---------------------------|--------------------------|
| name       | sum(amount) of type 1     | sum(amount) of type 2    |
|------------|---------------------------|--------------------------|
| Name_1     | 500 (as 100 + 400)        | 200                      |
|------------|---------------------------|--------------------------|
| Name_2     | 300                       | 0                        |
|------------|---------------------------|--------------------------|

How can I do it with Laravel? Or with MySQL?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2FDdXx8
via IFTTT

Aucun commentaire:

Enregistrer un commentaire