I've seen so many questions and answers on this subject, but I"m having trouble understanding what I'm doing wrong exactly. The query below gets all the information I need, but if it has multiple rows for when the r_num are the same and the r_order for each r_num are the same, then I only one result for each r_num. Right now though this call gives me errors. Can someone please explain to me how Distinct
works, and how I can use it in this query to achieve my goal?
SELECT DISTINCT po_num, r_num, r_order, vendor, order_date, received_by, received_date FROM(
SELECT p.id as po_num, r.id as r_num, r.rec_order as r_order, v.name as vendor, p.order_date, r.received_by, r.received_date
FROM Parts.dbo.po as p INNER JOIN
Parts.dbo.vendor as v ON v.id = p.vendor__id INNER JOIN
Parts.dbo.receipts as r ON r.id = 'R-'+CAST(p.id AS varchar)
GROUP BY p.id, r.id, r.rec_order, v.name, p.order_date, r.received_by, r.received_date) as tbl
GROUP BY r_num, r_order
Here is the error I get
Msg 8120, Level 16, State 1, Line 1
Column 'tbl.po_num' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.