2014-11-06 97 views
0

我在這個主題上看到了很多問題和答案,但我很難理解我在做什麼錯誤,下面的查詢獲取我需要的所有信息,但是如果它有多行,當r_num是相同的,並且每個r_num的r_order是相同的,那麼對於每個r_num我只有一個結果,現在雖然這個調用給了我錯誤,有人請向我解釋Distinct是如何工作的,我該如何使用它在此查詢實現我的目標是什麼?SQL Server不同,選擇所有行

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.

+0

你得到了什麼錯誤? – ekad 2014-11-06 16:11:37

+0

編輯顯示錯誤 – 2014-11-06 16:13:00

+0

錯誤說明了這一切......並且'DISTINCT'不是這裏的問題,它是你的分組 – Tanner 2014-11-06 16:14:35

回答

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 
+0

所以唯一的時間,然後我需要實際使用DISTINCT關鍵字是如果我試圖找到某些列的SUM,或者一個函數可能會發生多個結果? – 2014-11-06 16:21:40

+0

不完全:當您需要查找SUM()(或任何其他聚合)時使用'GROUP BY'。至於DISTINCT,只有在查詢中有多個完全相同的行時才需要它 - 它適用於所有返回的列。我通常會發現,在大多數情況下,在發生這種情況時,我會在JOIN中做錯事情... – AHiggins 2014-11-06 16:23:27

+0

啊,這很有道理,所以總結一下,確保我的JOIN在出發前是正確和簡潔的其他地方。 – 2014-11-06 16:24:29