Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

sql - MySQL Counting Distinct Values on Multiple Columns

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!)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just list multiple columns in the GROUP BY clause.

SELECT computer, user, count(*) AS count
FROM login
GROUP BY computer, user

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...