Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

agregate sales totals per years per customer in one transaction

i have a normal turnover table with 3 columns "customer" , "year", "amount"
(for example)

customer year amount
anton 2020 $5
paul 2019 $12
anton 2021 $5
paul 2019 $10
felicia 2021 $5
anton 2019 $12
felipe 2019 $12

and i have the following mysql query

SELECT `customer` , SUM(`amount`) as summ FROM `customer`.`accountsales` WHERE `amount`> 0 GROUP BY `customer` ORDER BY summ DESC ;

This transaction gives me a nice Paretto table with the sales of each customer in descending order

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

name sales all years
customer1 sum of all transactions of customer1
customer2 sum of all transactions of customer2
customer3 sum of all transactions of customer3

so far so good, i want to go one step further and i want to create the following table

Name Sales all years Sales 2021 Sales2020 Sales2019
customer1 sum1 sum2021 from customer1 sum2020 from customer1 sum2019 from customer1
customer2 sum2 sum2021 from customer2 sum2020 from customer2 sum2019 from customer2
customer3 sum3 sum2021 from customer3 sum2020 from customer3 sum2019 from customer3

but i want to do it in only one transaction, because the initial table is very huge.

can someone give a hint ?

p.S. feel free to edit the title since I am not very inspired today

>Solution :

You can try to use condition aggregate function

Query 1:

SELECT `customer` , 
       SUM(`amount`) 'Sales all years',
        SUM(CASE WHEN year = 2021 THEN `amount` ELSE 0 END)  Sales2021,
        SUM(CASE WHEN year = 2020 THEN `amount` ELSE 0 END)  Sales2020,
        SUM(CASE WHEN year = 2019 THEN `amount` ELSE 0 END)  Sales2019
FROM accountsales
GROUP BY `customer`

Results:

| customer | Sales all years | Sales2021 | Sales2020 | Sales2019 |
|----------|-----------------|-----------|-----------|-----------|
|    anton |              22 |         5 |         5 |        12 |
|  felicia |               5 |         5 |         0 |         0 |
|   felipe |              12 |         0 |         0 |        12 |
|     paul |              22 |         0 |         0 |        22 |
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading