SQL combines COUNT and SUM in a single query

I want to combine two SELECTs into one query, as shown 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 selections in one query to get the result

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

I am using SQLite3

+6
source share
1 answer
 SELECT COUNT(X), SUM(CASE WHEN Z = 1 THEN X ELSE 0 END) FROM tbl WHERE X>Y 
+15
source

Source: https://habr.com/ru/post/973729/


All Articles