How can I count unique items in sql?
-
I got help from here: for a query and from that I got this query: SELECT userID, COUNT(beerName) as NumberofBeers FROM uniqueBeers WHERE userID IN (3, 6) GROUP BY userID ORDER BY `uniqueBeers`.`userID` ASC this returns me a user id with how many beers they have in the database. Each row in this table is a beer and each beer by user is unique so I was able to get a count of unique beers by user. What I am trying to do now is, count unique breweries for each user. Unlike the last query where a user does not have doubles for a beer. They can for a brewery. I am lost on how to create a query that will count unique breweries for each user. Thanks!
-
Answer:
SQL supports the DISTINCT keyword inside some aggregate functions. SELECT userID, COUNT(DISTINCT beerName) AS NumberOfDistinctBeers FROM uniqueBeers WHERE userID IN (3, 6) GROUP BY userID ORDER BY userID ASC The meaning is that it only counts each distinct value once within each group. Without the DISTINCT, it will count every row where the expression is not NULL.
Bill Karwin at Quora Visit the source
Related Q & A:
- How can I optimize this dynamic SQL query in oracle with PL/SQL?Best solution by docs.oracle.com
- How can I get the count in SQL?Best solution by Stack Overflow
- How can I convert the query from SQL to LINQ?Best solution by Stack Overflow
- How can I create a cute, artsy, unique facebook profile?Best solution by Quora
- Where can I find which items I can write off as a 1099 contractor?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.