Chaddeus Chaddeus - 2 months ago 6
SQL Question

How do we select multiple columns in a sum()/group by query?

I have a requirement to pull a total # of product quantity from an Access DB, but include the vendor name, id number, description, etc... along with the sum of quantity.

I have a query like this:

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]


Works great... except I need to pull more columns in the query, something like this:

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]


Doesn't work, throws an aggregate error

So instead do something like so:

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]


Which runs but changes the results too much. What's the appropriate way to handle this query?

Answer

try this:

You have to make your first query as a derived table and join with the actual table to get all the fields

    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]