2017-04-27 85 views
0

我試圖執行一個查詢,顯示結果是供應商(Supp_Code)分組,然後在每個組,結果是通過委員會編(Comm_Code)訂購。排序由一羣查詢

下面的查詢:

sql = "SELECT [Comm_Code], [Supp_Code], [AqYear], [Product_Code], [Type], [Customer_Code], " & _ 
     "[Commission_Rate], [cType] FROM [Acquisition Commission] GROUP BY [Supp_Code] " & _ 
     "ORDER BY [Comm_Code]" 

Dim da As New OleDbDataAdapter(sql, con) 

Dim ds As New DataSet 
Dim dt As New System.Data.DataTable 

da.Fill(ds) 

給出了一個錯誤:

You tried to execute a query that does not include the specified expression 'Comm_Code' as part of an aggregate function.

我看這件事,並this answer說,這是因爲我包括在SELECTComm_Code但不是GROUP BY

所以,我把它改爲:

sql = "SELECT [Comm_Code], [Supp_Code], [AqYear], [Product_Code], [Type], [Customer_Code], " & _ 
     "[Commission_Rate], [cType] FROM [Acquisition Commission] GROUP BY [Supp_Code] " & _ 
     "ORDER BY [Comm_Code]" 

但後來我得到了同樣的錯誤,但與AqYear領域。

這將繼續下去,直到我將GROUP BY條款中的所有選定字段包含在內......當然,這會給我錯誤的輸出,但即使不是這樣,似乎也會有很多不必要的查詢。

有沒有更快/更好的方法來實現我期待的目標?或者,我是否需要在GROUP BY條款中包含每個查詢?

+0

一般的GROUP BY規則說:「如果指定了GROUP BY子句,則SELECT列表中的每個列引用都必須標識分組列或作爲set函數的參數。」 – jarlh

+1

你沒有對你的陳述進行任何分組。如果您只是希望將它們一起訂購,請將它們添加到order by子句中。 –

+1

按Supp_Code分組時,每個Supp_Code會得到一個結果行。由於表格中的一個Supp_Code可能有多個記錄,因此它的Comm_Codes中的哪一個,它的哪個AqYears,哪個Product_Codes等是你想要在結果行中看到的?你需要指定這個,例如MAX(Comm_Code),MIN(AqYear),... –

回答

2

我認爲你只是在尋找一個非聚集查詢有兩個ORDER BY鍵:

SELECT [Comm_Code], [Supp_Code], [AqYear], [Product_Code], [Type], [Customer_Code], 
     [Commission_Rate], [cType] 
FROM [Acquisition Commission] 
ORDER BY [Supp_Code], [Comm_Code]; 

GROUP BY查詢通常具有聚合函數,如COUNT()SUM()

0
-- group by Id & order by Name 

    SELECT id, name, dob FROM test GROUP BY id ORDER BY name 

嘗試這樣的事情..

乾杯!