Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

(Simple?) SQL Query: Display all customer information for customers with 2+ orders

I’m doing practice exam material for a distance education course. I have the following three relations (simplified here):

salesperson(emp#, name, salary)
order(order#, cust#, emp#, total)
customer(cust#, name, city)

I’m stuck on a pair of SQL queries.

  1. Display all customer info for customers with at least 1 order.
SELECT * FROM customer
  INNER JOIN order ON order.cust# = customer.cust#
  GROUP BY cust#;
  1. Display all customer info for customers with at least 2 orders.
SELECT cust#, name, city, industry-type FROM customer
  INNER JOIN order ON order.cust# = customer.cust#
  GROUP BY cust#
  HAVING COUNT(cust#) > 2;

I realize these are misguided attempts resulting from a poor understanding of SQL, but I’ve spent a ton of time on W3School’s SQL Query example tool (https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where) without getting anywhere, and I finally need some "real" help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try to use subquery to get count by cust# then do inner join to make it.

SELECT c.*
FROM (
    SELECT cust# , COUNT(*) cnt
    FROM order 
    GROUP BY cust#
) o INNER JOIN customer c ON c.cust# = o.cust#
WHERE o.cnt > 2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading