Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply where clause on only one of the selected value

Tags:

sql

php

mysql

Say I have a table like the following:

id    quantity
1       5
2       3
3       6

I want to retrieve the quantity of the row where id=2, and the total quantity of the table, 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 wrong, but I hope you can get the idea of what I am trying to do here. How can I achieve something like this?

like image 680
dshukertjr Avatar asked Mar 13 '23 07:03

dshukertjr


1 Answers

Use conditional aggregation:

select sum(case when id = 2 then quantity end) as qty2,
       sum(quantity) as total_quantity
from t;
like image 56
Gordon Linoff Avatar answered Mar 16 '23 04:03

Gordon Linoff