Search code examples
sqlmicrosoft-query

SQL sum, multiple Group By's and Date criteria


I'm looking to perform a sum calculation on a SQL table to find the quantity of a particular stock item held against a particular salesperson up to and including a specific date.

I'm able to perform the sum function to find the quantities on a Salesperson/item basis whenever I do not factor in the date range criteria, but as soon as i add that aspect, it all goes a bit pear shaped! Here is my code so far:

SELECT Salesperson, Item No, Sum(Quantity) AS 'Quantity'
FROM dbo
WHERE (Location Code='VAN')
GROUP BY Salesperson, Item No,
HAVING (Registering Date<={ts '2017-05-03 00:00:00'})

The location code = VAN filter is required to ensure it ignores Warehouse quantities.My SQL knowledge is limited to the few instances I run into it at work and my interaction is largely based through Microsoft Query in Excel. When looking at the above code, i figured that the 'Registering date' criteria should be in the 'WHERE' section, however when i add the criteria using the options available in Microsoft Query, it creates the 'HAVING' line.

If anyone could provide any pointers, it would be much appreciated!

Cheers

Peter


Solution

  • I would imagine a query like this:

    SELECT Salesperson, [Item No], Sum(Quantity) AS Quantity
    --------------------^ escape the non-standard column name
    FROM dbo.??
    ---------^ table name goes here
    WHERE Location Code = 'VAN' AND
          [Registering Date] <= '2017-05-03'
    ------^ put the filtering condition in the correct clause
    GROUP BY Salesperson, Item No
    -----------------------------^ remove the comma
    

    Your code, as written, has multiple errors. I am guessing that most are transcription errors rather than in the original query (queries don't run if no table is given in the FROM for instance). The "major" error would then be filtering in the HAVING clause rather than the WHERE clause.