0

I am trying to fetch distinct record from mysql table order by visit time which should be latest visit with below query:

SELECT COUNT(*) as cookie_id, id, lead_id
FROM analytics where lead_id != 0 and user_id = 1
GROUP BY lead_id 
HAVING cookie_id > 1 order by visit_time desc

But with above query i am getting wrong result.

** My Required result initial:**

2054, 2016-02-02 14:19:40
2051, 2016-02-02 13:54:17
2055, 2016-02-02 12:22:16
2039, 2016-02-02 11:46:49

My original data table screen attached.from below table i am trying to get filter result..

enter image description here

4
  • your required result shows two columns (seems like "lead id" and "visit time"), however your query is selecting three ("cookie id", "id" and "lead id"). Thats one reason why you are not getting the results you want.
    – CodeGodie
    Commented Feb 2, 2016 at 14:53
  • Hi. Thanx for suggestion. But this is my sample that i want to get. Its very sort of required result i need.
    – Naresh
    Commented Feb 2, 2016 at 17:25
  • Got it.. However you should provide the exact results you want, even if its just a sample, so that we can give you the right solution.
    – CodeGodie
    Commented Feb 2, 2016 at 17:28
  • Ok. Can you solve the issue and generate a query for my table which will give me required result .. I appreciate. I tried my 4 hours and not getting success
    – Naresh
    Commented Feb 3, 2016 at 2:32

4 Answers 4

2

This does what you are looking for

select lead_id, cookie_id, max(visit_time) as visit_time
from analytics
where lead_id != 0
and user_id = 1
group by lead_id, cookie_id
order by visit_time desc

be sure that you have indexes on lead_id, user_id and visit_time

0

you want GROUPWISE MAXIMUM of a column, an example exists in the manual here

1
  • Hi . thanx for you answer. I tried with after your ans but not getting wht is right query, i should try.
    – Naresh
    Commented Feb 3, 2016 at 2:30
0

This is very simple. For you to get your desired result(the required result you mentioned above). All you need to do is use GROUP BY like this:

SELECT lead_id, visit_time
FROM analytics
GROUP BY lead_id

Sample SQL: SQL FIDDLE

0

That was solution for me:

SELECT count(lead_id) as lead_id_count, lead_id, cookie_id, max(id) as max_id,max(visit_time)
FROM analytics where user_id =1 and lead_id != 0 GROUP BY cookie_id,lead_id HAVING lead_id_count > 1 ORDER BY id DESC LIMIT 0 ,10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.