SQL Server Distinct,选择所有行

时间:2014-11-06 16:09:44

标签: sql-server

我在这个问题上看到了很多问题和答案,但是我无法理解我的错误。下面的查询获取了我需要的所有信息,但是如果它有多行,那么r_num是相同的,每个r_num的r_order是相同的,那么我每个r_num只有一个结果。现在虽然这个调用给了我错误。有人可以向我解释Distinct如何工作,以及我怎么能在此查询中使用它来实现我的目标?

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

这是我得到的错误

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.

1 个答案:

答案 0 :(得分:1)

除非您正在进行聚合,否则您不需要同时拥有DISTINCT和GROUP BY。

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

如果您尝试获取不同的r_num和r_order值,则需要分组/仅选择这两列:

SELECT r_num, r_order
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

或者,如果您的数据可以处理它,请在额外列上使用聚合:

SELECT MAX(po_num) AS po_num, r_num, r_order, MAX(vendor) AS vendor -- etc.
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