1

me being a humble sql beginner, I have a question: let's say I have two tables: Items, and People(to whom an item is sold). Is there any way in SQL to produce a query to show data of a person who bought the most items, and the ammount of items he or she bought?

my creates are:

CREATE TABLE PEOPLE (
    ID INT PRIMARY KEY, 
    (other data)
);

CREATE TABLE ITEMS (
   ID INT PRIMARY KEY, 
   (other stuff....)
   bought_by INT REFERENCES PEOPLE
);

Any help would be appreciated:)

2 Answers 2

3

Yes, you can just group by bought_by from ITEMS table, sort the result descending by the count and get the top record:

select top 1 bought_by, count(*)
from ITEMS
group by bought_by
order by count(*) desc
Sign up to request clarification or add additional context in comments.

Comments

1

Probably this query can help you too, if you need more people data/info:

SELECT TOP 1 PEOPLE.*, COUNT(ITEMS.*) AMOUNT FROM PEOPLE 
    JOIN ITEMS ON PEOPLE.ID = ITEMS.bought_by
GROUP BY PEOPLE.ID, PEOPLE.OtherFieldsInPeopleTable 
ORDER BY COUNT(ITEMS.*) DESC

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.