Joining on a Subquery
suggest changeJoining a subquery is often used to show aggregate data from a child table next to rows from the parent table. For example, you might want a count of child rows, an average of a numeric column, or one row chosen by a date or a number. Aliases arguably make the query easier to read when several tables are involved. The query below returns every purchase order and the distinct line-item combinations for that order. Min(l.id) is computed, but it is not used to keep only the first line. Grouping by the item columns does not pick a single earliest row.
SELECT po.Id, po.PODate, po.VendorName, po.Status, item.ItemNo,
item.Description, item.Cost, item.Price
FROM PurchaseOrders po
LEFT JOIN
(
SELECT l.PurchaseOrderId, l.ItemNo, l.Description, l.Cost, l.Price, Min(l.id) as Id
FROM PurchaseOrderLineItems l
GROUP BY l.PurchaseOrderId, l.ItemNo, l.Description, l.Cost, l.Price
) AS item ON item.PurchaseOrderId = po.Id
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents