Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL unify COUNT and SUM in one query

Tags:

sql

sqlite

I want to combine two SELECTs into one single query, as the example below:

TABLE tbl

╔════╦════╦════╦═══╗
║ id ║ X  ║ Y  ║ Z ║
╠════╬════╬════╬═══╣
║  0 ║  1 ║  2 ║ 0 ║
║  1 ║  3 ║  0 ║ 1 ║
║  2 ║  5 ║  6 ║ 1 ║
║  3 ║  7 ║  8 ║ 0 ║
║  4 ║  9 ║  4 ║ 1 ║
║  5 ║ 11 ║ 10 ║ 0 ║
╚════╩════╩════╩═══╝

SELECT COUNT(X) FROM tbl WHERE X>Y
SELECT SUM(X) FROM tbl WHERE X>Y AND Z=1

the first SELECT returns 3 and the second 12. I want to combine the two selects in a single query to get the result

╔══════════╦════════╗
║ COUNT(X) ║ SUM(X) ║
╠══════════╬════════╣
║        3 ║    12  ║
╚══════════╩════════╝

I am using SQLite3

like image 210
user1925772 Avatar asked Aug 12 '14 22:08

user1925772


People also ask

Can SUM and count in same SQL query?

SUM() and COUNT() functions SUM of values of a field or column of a SQL table, generated using SQL SUM() function can be stored in a variable or temporary column referred as alias. The same approach can be used with SQL COUNT() function too.

How do you write a SUM and count in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.

Can I use SUM and Max in same query?

SUM() and MAX() at the same time Notice that all aggregate functions except COUNT(*) ignore the NULL Rating for the ID=5 row. COUNT(*) counts rows, whereas COUNT(col) counts non-null values. So to answer your question, just go ahead and use SUM() and MAX() in the same query.

Can we use max and count together in SQL?

No, we can't use a MAX(COUNT(*) and we can not layer aggregate functions on top of one another in the same SELECT clause.


1 Answers

SELECT 
    COUNT(X),
    SUM(CASE WHEN Z = 1 THEN X ELSE 0 END) 
FROM tbl WHERE X>Y
like image 157
FuzzyTree Avatar answered Sep 20 '22 01:09

FuzzyTree