Sum data query request
(1) By anonymous on 2021-03-23 14:42:38 [source]
Hi All,
I could use some assistance with a query. If you have the time, I'd appreciate some pointers.
I want to have A
, B
and C
from col1 summed with their corresponding values in col2.
For exaple:
AAA,sum_total
BBB,sum_total
CCC,sum_total
sample data:
col1,col2
AAA,56000
AAA,58000
AAA,60000
AAA,64000
BBB,14280000
BBB,14298000
BBB,18396000
BBB,142640
CCC,6170000
CCC,6196000
CCC,6182000
CCC,5930000
CCC,5878000
CCC,5910000
CCC,6002000
BBB,18302000
BBB,18320000
BBB,18234000
AAA,32000
AAA,36000
AAA,38000
(2) By Stephan Beal (stephan) on 2021-03-23 15:12:22 in reply to 1 [link] [source]
I want to have A, B and C from col1 summed with their corresponding values in col2. For exaple:
Assuming the input you pasted in above is in the file foo.csv
:
$ sqlite3
SQLite version 3.35.3 2021-03-20 01:00:26
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> create table t(a,b);
sqlite> .import --skip 1 --csv 'foo.csv' t
sqlite> select a, sum(b) from t group by a;
AAA|344000
BBB|101972640
CCC|42268000
(3) By Ryan Smith (cuz) on 2021-03-23 17:02:32 in reply to 1 [link] [source]
This is the poster-child use-case for aggregate functions. It's precisely why they exist.
Stephen already gave a valid good query, I'll add a note or two:
- You may also Sort the rows at the same time This should work on your DB:
SELECT col1, SUM(col2)
FROM {your table}
GROUP BY col1
ORDER BY col1
- SUM() and TOTAL() both work and both add up all the non-NULL values in a group. If you think your values may contain NULLs, you can use TOTAL() which will produce a non-NULL answer (such as 0.0) even if all the values in a group is NULL. SUM() on the other hand will return NULL in that case - which may be unwanted.
SELECT col1, TOTAL(col2)
FROM {your table}
GROUP BY col1
- You can use any other aggregate function in the same way. Some examples:
SELECT col1, SUM(col2), COUNT(col2), AVG(col2), MIN(col2), MAX(col2)
FROM {your table}
GROUP BY col1
Good luck!