0

I have 4 tables

Table: Category
    CategoryID (int)
    Name (varchar)
Table: Products
    ProductID (int)
    CategoryID (int)
    Name (varchar)
    Description (text)
Table: Sales
    SalesID (int)
    ProductID (int)
Table: Links
    LinkID (int)
    ProductID (int)

Now I need to display data as:

CategoryName     Total Products     Total Sales     Total Links
    ABC                5                 12            50
    XYZ               12                 26            10

How can I achieve this, may be in single query

Help appreciated

Thanks

5
  • I can see how you would relate Products, Sales, and Links, but what column links Category in with these? Commented Dec 13, 2010 at 7:37
  • yes, obviously there is a missing link here. Commented Dec 13, 2010 at 7:47
  • Edited: I added CategoryID to products table Commented Dec 13, 2010 at 7:52
  • 1
    @I-M-JM: for reference, SQL JOINs, GROUP BY and aggregate functions. Commented Dec 13, 2010 at 8:08
  • Can you add PK and FK to your tables? Commented Dec 13, 2010 at 9:06

1 Answer 1

1
SELECT c.Name AS "CategoryName", COUNT(p.ProductID) AS "TotalProducts", COUNT(s.SalesID) AS "TotalSales", COUNT(l.LinkID) AS "TotalLinks"
FROM Category c
INNER JOIN Products p ON p.CategoryID = c.CategoryID
INNER JOIN Sales s ON s.ProductID = p.ProductID
INNER JOIN Links l ON l.ProductID = s.ProductID;

I don't know how the data looks like but you may need to add a GROUP BY somewhere if you have duplicates or an optional ORDER BY if you need sorting in any of the columns

Sign up to request clarification or add additional context in comments.

1 Comment

by the way, I replaced inner join to left join, and it helped.

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.