33

I wrote a script that runs each time a user logs into a computer in our domain. This script makes a record of the user as well as the computer they logged into. Any number of users can log into any number of computers.

I just inherited this IT environment from a consultant who is no longer around, and I'm writing this little query so when I get a call from a user, I can search by that user's name and reasonably predict which computer they are using by the number of times they've logged into any given computer.

Here's a sample of the data in the 'login' table:

    COMPUTER        USER
    ncofp02         lee
    ncofp02         lee
    ncofp02         andy
    ncodc01         andy
    ncodc01         andy
    ncodc01         lee

What I'm banging my head on is the logic to count distinct values across multiple columns. I'd like to see a result like this:

    COMPUTER       USER   COUNT
    ncofp02        lee    (2)
    ncofp02        andy   (1)
    ncodc01        lee    (1)
    ncodc01        andy   (2)

Is there a way to accomplish this with a single query within mysql, or should I start looping some php? (booooo!)

3 Answers 3

65

Just list multiple columns in the GROUP BY clause.

SELECT computer, user, count(*) AS count
FROM login
GROUP BY computer, user
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I can't believe it was seriously THAT easy. LOL I guess I must have been overthinking. Thanks again!
7

Try this:

SELECT l.computer, l.user, COUNT(DISTINCT l.computer, l.user) AS count
FROM login l 
GROUP BY l.computer, l.user

1 Comment

You don't need DISTINCT if you're counting the same thing you're grouping by.
3

Easy!

SELECT 
    computer, user, COUNT(DISTINCT computer, user) AS count
FROM 
    login 

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.