Skip to content
Advertisement

Postgres join and count multiple relational tables

I want to join the 2 tables to the first table and group by a vendor name. I have three tables listed below.

Vendors Table

| id         |      name 
|:-----------|------------:|
| test-id    | Vendor Name |    

VendorOrders Table

| id         | VendorId    | Details      | isActive(Boolean)| price |
|:-----------|------------:|:------------:| -----------------| --------
| random-id  |   test-id   |  Sample test |   TRUE            | 5000

OrdersIssues Table

| id         | VendorOrderId| Details.   |
|:-----------|--------------:-----------:|
| order-id   |   random-id  | Sample test|   

The expected output is to count how many orders belong to a vendor and how many issues belongs to a vendor order.

I have the below code but it’s not giving the right output.

SELECT "vendors"."name" as "vendorName", 
COUNT("vendorOrders".id) as allOrders,
COUNT("orderIssues".id) as allIssues 
FROM "vendors" 
LEFT OUTER JOIN "vendorOrders" ON "vendors".id = "vendorOrders"."vendorId" 
LEFT OUTER JOIN "orderIssues" ON "orderIssues"."vendorOrderId" = "vendorOrders"."id"
GROUP BY "vendors".id;```

Advertisement

Answer

You need the keyword DISTINCT, at least for allOrders:

SELECT v.name vendorName, 
       COUNT(DISTINCT vo.id) allOrders,
       COUNT(DISTINCT oi.id) allIssues 
FROM vendors v
LEFT OUTER JOIN vendorOrders vo ON v.id = vo.vendorId 
LEFT OUTER JOIN orderIssues oi ON oi.vendorOrderId = vo.id
GROUP BY v.id, v.name;

Consider using aliases instead of full table names to make the code shorter and more readable.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement