Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL ,How to count rows in range

Tags:

sql

select

mysql

I have two table:

One is a_tbl(uid, login_ip, login_time);

here ip is a 32 bit integer, time is the unix timestamp.

another is b_tbl(country, province, city, ip_from, ip_to)

I want to find out that each range in b_tbl has how many unique uid in a_tbl.

Notice that b_tbl has a lot of unique rows, and a_tbl may exist dunplicated uid.

Thank you very much.

like image 804
user1928099 Avatar asked Jul 31 '26 19:07

user1928099


2 Answers

To implement this, you can write a JOIN using BETWEEN as its predicate. That will develop the ranges; then, just count the items falling in each range. Something like this should get you started:

SELECT b_tbl.ip_From, b_tbl.ip_to, COUNT(a_tbl.login_ip)
  FROM a_tbl
  JOIN b_tbl ON a_tbl.login_ip BETWEEN b_tbl.ipfrom AND b_tbl.ip_to
GROUP BY  b_tbl.ip_From, b_tbl.ip_to;
like image 180
MikeB Avatar answered Aug 03 '26 10:08

MikeB


try this:

SELECT ip_from
    , ip_to
    , COUNT(distinct uid) as NumberOfUniqueUserId
FROM a_tbl
INNER JOIN b_tbl on login_ip BETWEEN ip_from AND ip_to
GROUP BY ip_from
    , ip_to
like image 35
Umed Jan Avatar answered Aug 03 '26 08:08

Umed Jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!