Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

sql - Calculate ratio two tables

Table1 has a "call" column and Table2 has a "pickup" column.

I want to find the call to pickup ratio but can't wrap my head around it.

I am using sqlite. I have tried this

SELECT (SELECT count (call)FROM table1)*100/ (SELECT count (pickup) FROM table2)

but I get a number and not a decimal back

question from:https://stackoverflow.com/questions/65858662/calculate-ratio-two-tables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SQLite does integer division. So, 1/2 is 0 rather than 0.5.

So, the simplest method is to use 100.0 instead of 100:

SELECT ((SELECT count(call) FROM table1) * 100.0 /
        (SELECT count(pickup) FROM table2)
       ) as call_to_pickup_ratio

This, in turn, runs the ricks of a divide by zero. The solution for that is NULLIF():

SELECT ((SELECT count(call) FROM table1) * 100.0 /
        (SELECT NULLIF(count(pickup), 0) FROM table2)

Finally, if call and pickup are never NULL, then you can just use COUNT(*):

SELECT ((SELECT count(*) FROM table1) * 100.0 /
        (SELECT NULLIF(count(*), 0) FROM table2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...