简体   繁体   中英

Select multiple variables in SQL

So I have the following problem.

I have a receipts table with several columns, among others I have 2 columns 'receipt_id' and other 'status' .

'Status' can take the following values: 'active' and 'unpaid' .

I would like to run a query to have an output of the following ratio (lets call it 'RR') RR=active/(active+unpaid)

I've tried to make 'RR' as a variable and then input the arguments with their conditions using 'AS' function.

Also I've tried to make the following:

select count(distinct r.user_id) from receipts as r where r.status='active' as active, count(distinct r.user_id) from receipts as r where r.status='unpaid' as unpaid

(in order to get two different columns and the make the ratio 'RR' with a simple formula).

None of this is working...

Could someone please help me? Thanks in advance

Just use conditional aggregation. I think this is the simplest method:

select avg(r.status = 'active')
from receipts r
where r.status in ('active', 'unpaid');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM