简体   繁体   中英

SQL - better way to group and sum based on condition

I have data like:

Year Amount
2001 1
2020 2
2020 2
2021 5
2022 2
2022 2
2021 2

And I want to summarise data like:

Year Amount
2020 and before 5
2021 7
2022 4

I thought of 2 ways, and want to see whether there are any better method.

  1. Use Union
Select Year, sum(Amount) from TABLE_A 
where Year <= 2020
UNION
Select Year, sum(Amount) from TABLE_A 
where Year > 2020
  1. Added a new column
SELECT YR, SUM(Amount) FROM
(
  SELECT CASE WHEN Year <= 2020 THEN '2020_and_before') ELSE Year END as YR, * 
  FROM TABLE_A ) A
GROUP BY YR

I can get the results I want, but want to see whether there is better method

In MySQL, you can avoid subqueries with a CASE expression in the following way:

SELECT CASE WHEN Year_ <= 2020 THEN "2020 or before"
            ELSE Year_ END AS Year_ ,
       SUM(Amount) AS total_amount
FROM tab       
GROUP BY 1

Output:

Year_ total_amount
2020 or before 5
2021 7
2022 4

Check a MySQL demo here .

Note : You should avoid messing with data types. If you're supposed to store years in the year field, you could leave the integer 2020, instead of having a string like "2020 or before".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM