我们如何通过查询在sum()/ group中选择多个列?

时间:2012-07-31 06:27:45

标签: sql ms-access-2007

我要求从Access数据库中提取总产品数量#,但包括供应商名称,ID号,描述等......以及数量总和。

我有这样的查询:

SELECT [Vendor Name], SUM([Quantity]) AS Total
FROM [SalesDB]
WHERE [Vendor No] IN (1,2,3,4,5,6,7,8) AND [Item Description] = 'bolts'
Group By [Vendor Name]

效果很好......除了我需要在查询中添加更多列,如下所示:

SELECT [Vendor Name], [Vendor No], [Item No], [Item Description], [Item Cost], [Quantity],  SUM([Quantity]) AS Total
FROM [SalesDB]
WHERE [Vendor No] IN (1,2,3,4,5,6,7,8) AND [Item Description] = 'bolts'
Group By [Vendor Name]

不起作用,抛出聚合错误

所以做一些像这样的事情:

SELECT [Vendor Name], [Vendor No], [Item No], [Item Description], [Item Cost], [Quantity],  SUM([Quantity]) AS Total
FROM [SalesDB]
WHERE [Vendor No] IN (1,2,3,4,5,6,7,8) AND [Item Description] = 'bolts'
Group By [Vendor Name], [Vendor No], [Item No], [Item Description], [Item Cost], [Quantity]

哪个运行但是过多地改变了结果。处理此查询的适当方法是什么?

2 个答案:

答案 0 :(得分:6)

试试这个:

您必须将第一个查询作为派生表进行,并与实际表连接以获取所有字段

    SELECT A.[Vendor Name], [Vendor No], [Item No], [Item Description], 
[Item Cost], [Quantity],B.Total
 from [SalesDB] A 
 inner join
    (SELECT [Vendor Name], SUM([Quantity]) AS Total
    FROM [SalesDB]
    WHERE [Vendor No] IN (1,2,3,4,5,6,7,8) 
    AND [Item Description] = 'bolts'
    Group By [Vendor Name])B
  on A.[Vendor Name]=B.[Vendor Name]

答案 1 :(得分:0)

只是一个想法

SELECT 
        [ItemID],
        SUM(ItemQty) as 'QTY',
        [ItemName] as 'ItemName',
        itemPrice as 'itemPrice',
        SUM(ItemTotalPrice) as  'Total'
    FROM
        [OrderDetails]
        inner join Orders
        on [OrderDetails].OrderID=Orders.OrderID
         where Orders.TableID != 4
    GROUP BY  ItemID, [ItemName],itemPrice order by ItemID