SQL Query to find the value which has max number of occurrences in a table without nesting

StackOverflow https://stackoverflow.com/questions/21491964

Pergunta

I'm working on the following schema (bold text stands for pk, and ":" stand for referenced tables) :

USERS(username, name, surname);

PRODUCTS(id, name, quantity);

PURCHASES(user:USERS, product:PRODUCTS, dateAndTime, quantityPurchased);

I want to find name and surname of the user who has made the max number of purchases.

Firstly I use a nested query to find out the number of purchases for each user and then I select the user which purchased >= ALL those values:

SELECT name, surname, username
FROM users JOIN purchases ON username = user
GROUP BY name, surname, username
HAVING count(*) >= ALL(
    SELECT count(*)
    FROM utenti JOIN acquisti ON username = user
    GROUP BY username)

Is there another way to achieve the same without using nested queries?

Thank you in advance for your time.

Foi útil?

Solução

Yes there is. This sounds like a homework assignment, but you seem to have put some work into it. The idea is to order by the count(*) and take the first row. The syntax in SQL Server, Sybase, and Access is:

SELECT top 1 name, surname, username
FROM users as u INNER JOIN
     purchases as p
     ON u.username = p.user
GROUP BY name, surname, username
ORDER BY count(*) desc;

Other databases would put a limit 1 clause after the order by, instead of top 1. And others may have even more arcane syntax.

Outras dicas

This will return the user with most purchased items.

SELECT TOP 1
   U.name, U.surname, SUM(P.quantityPurchased) Purchases
FROM users U
  JOIN purchases P
    on U.username= P.user
GROUP BY U.username, U.name, U.surname
ORDER BY Purchases DESC

and this will return the user with most purchaes.

SELECT TOP 1
   U.name, U.surname, COUNT(*) occurrences
FROM users U
  JOIN purchases P
    on U.username= P.user
GROUP BY U.username, U.name, U.surname
ORDER BY occurrences DESC
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top