按查询分组排序

Ordering By a Group By Query

我正在尝试执行查询以显示按 供应商 (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 说这是因为我在 SELECT 中包括了 Comm_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 子句中包含所有选定的字段...当然这会给我错误的输出,但即使没有,看起来也有很多不必要的查询。

是否有 faster/better 方法来实现我的目标?还是我只需要在 GROUP BY 子句中包含每个查询?

我认为您只是在寻找具有两个 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()

-- group by Id & order by Name

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

试试这样的东西..

干杯!!