SQL sum, multiple Group By's and Date criteria - sql

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

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.

Related

Pie Chart in Report Builder is divided in lots pieces?

My Query creates lots of entries because there are a lot of entries for dates in the view, and when I try to filter out the information in report builder it doesn't divide the pie graph into four pieces but divides it into the number of date entries in the view.
What I am supposed to do is get number parts sold for each class between dates. The dates are to be selected in report builder.
SQL Developer Query:
CREATE OR REPLACE VIEW QUERY3 AS
SELECT partclass, COUNT(p.partno) AS "Parts Sold", orderdate
FROM part p, salesorder s, orderprod o
WHERE p.partno = o.partno
AND o.orderno = s.orderno
GROUP BY partclass, orderdate;
Report Builder Query
SELECT * FROM QUERY3
You didn't post a query you use in Reports Builder. Apparently, you'll need to include a WHERE clause which restricts the result set by dates. Something like this:
select partclass, "Parts Sold", orderdate
from query3
where orderdate between :par_date_from and :par_date_to; --> this
A side note: consider recreating the view and naming the "Parts Sold" column differently, such as parts_sold. The way you put it, you'll always have to reference that column using double quotes and paying attention to mixed case.
:par_date_from and :par_date_to represent references to parameters you should create in the report. If you use the built-in Parameter Form, you'll be prompted to enter those values. Or, if you run the report differently, you'll have to pass those values to the report in order to use them.

SSRS 2008 R2 - How to aggregate group data based on inner group filters?

I have made a simplified example to illustrate the question i'm trying to ask here. In my example i have sales orders and each sales order has multiple lines, i group by Sales Order Number, then by Sales Order Line (row groups)
I have found Group Filters very useful/flexible in filtering report data in specific areas of a table, so in my example i filter the SOLine group to exclude the SO line if it equals 3.
Then, i want to have a group aggregate for the entire SO, to tell me a count of the SO lines within it. Unfortunately when doing COUNT() expression from a textbox within the Sales Order Number group scope it counts all the lines, including the SO Line 3, whereas i want it to take into consideration the line filtered out from its child group.
Below is a screenshot of my tablix and grouping:
On the SOLine group i have the following filter:
And below is the output i get when previewing the report:
I want that count to evaluate to 4, but i ideally want to keep using groups as i've found they are much more efficient than using SUM(IIF) which completely slowed down my actual report which has thousands of rows.
If this is not possible, please give all best alternatives i could use.
Many thanks.
Jacob

How to find the sum of a column generated from a query

So, I'm im doing a ticket style database and i'm trying to find the sum of the tickets generated from this. I have attached my query below and the result of it
QUERY RESULT
SELECT Price, TicketID, Ticket.TicketType
FROM Price, Ticket
WHERE Price.TicketType = Ticket.TicketType
;
In the picture, I am trying to get a total for all of the prices that you see in there, each ticketID is a new ticket sold. I can click the totals button in access and it puts a total below it, but I need the total done in the query, so I am wondering how I could do this.
First, learn to use proper join syntax. Commmas in the FROM clause are simply an archaic way to represent a join.
From what you say, you want sum():
SELECT SUM(Price)
FROM Price JOIN
Ticket
ON Price.TicketType = Ticket.TicketType;
This may or may not do exactly what you want. It answers the question quite specifically.
Use the SUM function:
http://www.w3schools.com/sql/sql_func_sum.asp
I think this can help

SQL grouping with "Invalid use of group" error

I'll be upfront, this is a homework question, but I've been stuck on this one for hours and I just was looking for a push in the right direction. First I'll give you the relations and the hw question for background, then I'll explain my question:
Branch (BookCode, BranchNum, OnHand)
HW problem: List the BranchNum for all branches that have at least one book that has at least 10 copies on hand.
My question: I understand that I must take the SUM(OnHand) grouped by BookCode, but how do I then take that and group it by BranchNum? This is logically what I come up with and various versions:
select distinct BranchNum
from Inventory
where sum(OnHand) >= 10
group by BookCode;
but I keep getting an error that says "Invalid use of group function."
Could someone please explain what is wrong here?
UPDATE:
I understand now, I had to use the HAVING statement, the basic form is this:
select distinct (what you want to display)
from (table)
group by
having
Try this one.
SELECT BranchNum
FROM Inventory
GROUP BY BranchNum
HAVING SUM(OnHand) >= 10
You can also find Group By Clause with example here.
Although all comments in the question seem to be valid and add information they all seem to be missing why your query is not working. The reason is simple and is strictly related by the state/phase at which the sum is calculated.
The where clause is the first thing that will get executed. This means it will filter all rows at the beginning. Then the group by will come in effect and will merge all rows that are not specified in the clause and apply the aggregated functions (if any).
So if you try to add an aggregated function to the where clause you're trying to aggregate before data is being grouped by and even filtered. The having clause gets executed after the group by and allows you to filter the aggregated functions, as they have already been calculated.
That's why you can write HAVING SUM(OnHand) >= 10 and you can't write WHERE SUM(OnHand) >= 10.
Hope this helps!

Microsoft Access 2003 - creating a separate field that totals 5 other fields from the table

This is what i have so far in the SQL code........
SELECT DISTINCTROW [OEE/A Query].Press,
Sum([OEE/A Query].[SumOfLabor Hours]) AS [Sum Of SumOfLabor Hours],
Sum([OEE/A Query].[SumOfGood Pieces]) AS [Sum Of SumOfGood Pieces],
Sum([OEE/A Query].[Scrap Pieces]) AS [SumOfScrap Pieces],
Sum([OEE/A Query].[SumOfMachine Hours]) AS [SumOfSumOfMachine Hours],
Sum([OEE/A Query].[Total Parts Hours Earned]) AS [SumOfTotal Parts Hours Earned],
Sum([OEE/A Query].[Standard Pcs Expected]) AS [Stand Pcs Expected]
FROM [OEE/A Query]
GROUP BY [OEE/A Query].Press;
How do i add to this code another field that totals 5 separate other fields?
Here's what i think it might look like but I'm not sure.....
SELECT Sum(Sort+Straighten+Shine+Standardize+Sustain)
SUM(Sort),
SUM(Straighten),
SUM(Shine),
SUM(Standardize),
SUM(Sustain),
FROM [Shift Report Table];
it depends on what you are really asking. I am not sure if your second query is just another example, or, if it is in fact a different data source to be added into your first query.
If you want to add another column to your first query example based on the columns that already exist in your query then yes, simply add them together, as per CK says.
e.g.
select sum(column1) + sum(column2) as sum_c1_c2
or
select sum(column1 + column2) as sum_c1_c2
when doing aggregate functions I have an old habit of handling NULL values to make sure I am getting the results I think I should be getting. e.g.
select sum(nz(column1,0) + nz(column2,0)) as sum_c1_c2
Now if you are asking how to add a new column from a different data source, then you can either join to that other datasource, or, if returning just a single value, can use an inline select.
Also, a word of warning about distinctrow - I am not sure you want to use that in your query. You are doing a group by, so only the unique values for [press] will be selected with the aggregated columns as per your SUM() function. It is really hand for things like determining if (by way of example) a Product has been ordered e.g.
select DISTINCTROW productname
from products
inner join orders on orders.productid = products.productid
will return just 1 row so there is no chance for any aggregation in the above case.
But you might want to clarify your requirement a bit more. CK might have already given the answer, or, we might need to include a different datasource (such as your second query).
Yes, that is correct. You can add fields within the sum function, to sum the sum of the fields.