Saturday, April 23, 2011

Emulating analatic

For example you are working on a "user" table in mysql with following fields user_id,client_id,phone_no

Every day you assigned a new client id to the user phone_no.For any time when u inserting that data into new table you are taking only that user_id which client id is max for that phone_no.

Now in your table current data is

user_id|client_id|phone_no
-----------------------------
17|1013|9876543
1017|5013|9876544
10017|3013|9876543
100017|4013|9876543
1000017|13|9876544

now when you want to use this data for inserting into new table.

You need to calculate max user id for the phone no which client id is max.
It means

when u process for phone no 9876543

then you have to used user_id 100017 either it is 17,10017,100017

as well as if you process for phone_no 9876544

then you should use user_id 1017 either it is 1017,1000017 because for 1017 client_id max.

You are not going to do this manually

The part of query that gives you max user_id for all phone_no's max client id is called Emulating analatic(AKA ranking)

select user_id,client_id,phone_no from user as t1 where (select count(*) from user as t2 where t2.client_id>t1.client_id and t1.phone_no=t2.phone_no)=0)

user_id|client_id|phone_no
1017|5013|9876544
100017|4013|9876543


and after you can inner join this with user on phone_no and take user_id from user table and max user id is the user_id for that phone_no from Emulating analatic(AKA ranking).

Final query is

select user.user_id as user_id,temp.user_id as max_user_id from user inner join (select user_id,client_id,phone_no from user as t1 where (select count(*) from user as t2 where t2.client_id>t1.client_id and t1.phone_no=t2.phone_no)=0)temp on temp.phone_no=user.phone_no

And you got
user_id|max_user_id
17|
100017
1017|1017
10017|
100017
100017|100017
1000017|1017

Now for any other table when u want to insert the user_id you need to insert max_user_id for the corrosponding user_id.

No comments: