1

I save user logins in a table that named loginstats, I want to retrieve last login of every users, I use these code but I meet some error, What is my mistake?

select *
from loginStats
where id in (
    select distinct username, MAX(id) as id
    from loginStats
    group by username)
1
  • What is "id" and how does it relate to "last login"? And why are you doing a sub-select? Perhaps you can explain (a) your schema and (b) what error you are getting? Commented Feb 27, 2012 at 19:23

5 Answers 5

2

You are doing id IN, but are trying to compare it to multiple columns. Try this instead:

SELECT A.*
FROM LoginStats A
INNER JOIN (SELECT DISTINCT username, MAX(id) as id
            FROM loginStats
            GROUP BY username) B
ON A.username = B.username AND A.id = B.id
Sign up to request clarification or add additional context in comments.

Comments

1
select *
from loginStats
where id in (
    select distinct MAX(id) as id
    from loginStats
    group by username)

You can't have multiple field outputs in your IN subquery.

Comments

1

Or you could also do this like this:

;WITH CTE
AS
(
    SELECT 
        RANK() OVER(
                    PARTITION BY loginStats.username 
                    ORDER BY loginStats.id DESC
                ) AS iRank,
        loginStats.*
    FROM 
        loginStats
)
SELECT
    *
FROM
    CTE
WHERE
    CTE.iRank=1

Here is some information how to use the rank function and how it is applied.

Here is some information on msdn about the rank function.

Here is some information about cte function and usage

Here is some information about With clause and how it is used

Hope it helps you understand

2 Comments

Thanks, But I don't now these functions and word keys RANK(), Partition By, CTE. If you have some source that I learn from it, introduce.
No problem. I just think that if you understand this function you can write better queries. Maybe a +1 for the help?
0

The mistake is that in the IN clause only one column can be specified and you are specifying two: username and id.

Comments

0

You're selecting two fields, where you should only return one. This correlated subquery should work for you:

select *
from loginStats AS a
where id = (
    select MAX(id) as id
    from loginStats AS b
    where b.username = a.username)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.