Apply the where clause to only one of the selected value

Let's say I have a table like the following:

id    quantity
1       5
2       3
3       6

I want to get the number of rows, where id = 2, and the total number of tables, I thought I could do something like the following:

 sql="select quantity where id='2' sum(quantity) as total_quantity from table";

Now, I know that this statement is false, but I hope you can get an idea of ​​what I'm trying to do here. How can I achieve something like this?

+4
source share
2 answers

Use conditional aggregation:

select sum(case when id = 2 then quantity end) as qty2,
       sum(quantity) as total_quantity
from t;
+5
source

Use the union:

SELECT quantity FROM table WHERE id = 2
UNION SELECT SUM(quantity) FROM table
+2
source

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


All Articles