I have a query that filters results for products which have had orders sent after an user-input date, and calculates what the quantity becomes if the order was sent after that date.
SELECT id, ProductName,
[OnHand]+ SUM([OrderJoin.Quantity]) AS Qty After
FROM Query3
WHERE Query3.ShippedDate > [Enter End Date] And
Query3.ShippedDate) Is Not Null
GROUP BY id, ProductName, OnHand;
But if I were to remove the WHERE statement, how would I make it so the Qty After would show as OnHand for the results that become NULL?
You would use NZ() to convert the NULL value to 0. Something like this:
SELECT id, ProductName,
NZ(OnHand, 0) + NZ(SUM([OrderJoin.Quantity]), 0) AS QtyAfter
...
Related
I am trying to run a query to gather the total items on hand in our database. However it seems i'm getting incorrect data. I am selecting selecting just the amount field and summing it using joins from separate tables based on certain parameters, however if I display additional fields such as order number, and date all of a sudden im getting different data, even though those fields are being used as filters in the query. Is it because its not in the select statement? If it needs to be in the select statement is it possible to not display them?
Here are the two queries.
-- Items On Hand
select CONVERT(decimal(25, 2), SUM(tw.amount)) as 'Amt'
from [Sales Header] sh
join
(
select *
from TWAllOrders
where [Status] like 'Released'
) tw
on tw.[Order Nb] = sh.No_
join
(
select *
from OnHand
) oh
on tw.No_ = oh.[Item No_]
where sh.[Requested Delivery Date] < getdate()
HAVING SUM(tw.Quantity) <= SUM(oh.Qty)
providing a sum of 21667457.20
and with the added columns
-- Items On Hand
select CONVERT(decimal(25, 2), SUM(tw.amount)) as 'Amt', [Requested Delivery Date], sh.No_, tw.[Status]
from [Sales Header] sh
join
(
select *
from TWAllOrders
where [Status] like 'Released'
) tw
on tw.[Order Nb] = sh.No_
join
(
select *
from OnHand
) oh
on tw.No_ = oh.[Item No_]
where sh.[Requested Delivery Date] < getdate()
group by sh.[Requested Delivery Date], sh.No_, tw.[Status]
HAVING SUM(tw.Quantity) <= SUM(oh.Qty)
order by sh.[Requested Delivery Date] ASC
Providing a sum of 12319998
I'm self taught in SQL so I may be misunderstanding something obvious, thanks for the help.
With no sample data, I am going to have to demonstrate this in principle. In the latter query you have a GROUP BY meaning the scope of the values in the HAVING will differ, and thus the filtering from said HAVING will be different.
Let's take the following sample data:
CREATE TABLE dbo.MyTable (Grp char(1),
Quantity int,
Required int);
INSERT INTO dbo.MyTable (Grp, Quantity, [Required])
VALUES('a',2,7),
('a',14,2),
('b',4, 7),
('b',3,4),
('c',17,5);
Now we'll perform an overly simplified version of your query:
SELECT SUM(Quantity)
FROM dbo.MyTable
HAVING SUM(Quantity) > SUM(Required);
This brings back the value 40; which is the SUM of all the values in Quantity. A value is returned because the total SUM of Required is 25.
Now let's add a GROUP BY like your second query:
SELECT SUM(Quantity)
FROM dbo.MyTable
GROUP BY Grp
HAVING SUM(Quantity) > SUM(Required);
Now we have 2 rows, with the values 16 and 17 giving a total value of 33. That's because the rows where Grp have a value of 'B' are filtered out, as the SUM of Quantity is lower that Required for 'B'.
The same is happening in your data; in the grouped data you have groups where the HAVING condition isn't met, so those rows aren't returned.
I want to pass a parameter of list of strings of product types into my SQL statement and want it to check if it is null or not and select all the rows where the productType and or color matches the rows. I'm essentially trying to implement filters.
SELECT productName, productType, cost, color
FROM inventory
WHERE CASE(
WHEN( (productType IN :typeList) IS NOT NULL
THEN (SELECT * FROM inventory WHERE productType IN
:typeList)
WHEN(color in :colors) IS NOT NULL THEN (SELECT * FROM
inventory WHERE color IN:typeList)
END
)
What is wrong with:
SELECT productName, productType, cost
FROM inventory
WHERE productType IN :typeLIST
I want to find the total outstanding amount for a particular item amount excluding the refund amount.
There will be two columns for each item based on number of times it was sold, final_amount and 2nd refund_amount for each items and I want to subtract total refund_amount from final_amount for each item.
PFB the code/query
SELECT item_id,
SUM(final_amount) as total_amount,
SUM(ISNULL(refund_amount, 0)) AS total_refund
SUM(final_amount) - SUM(ISNULL(refund_amount, 0)) AS outstanding_amount
FROM tabel1
WHERE item_id in ('119688521',
'109536343',
'99459466',
'97126817',
'138148320',
'107816131')
GROUP BY 1
I am getting a syntax error for "SUM" near
SUM(final_amount)-SUM(ISNULL(refund_amount, 0)) AS outstanding_amount
I tried different code:
SUM(total_amount - total_refund) AS npv
And I got the same error.
First off, there's a few errors in syntax. You're missing a comma between all the select-elements (between your total_refund and outstanding_amount). You should also check if the SUM() was null, not if the column was null. You can also use COALESCE() if you prefer that. Finally, you need to GROUP BY something useful, like the item_id.
SELECT item_id,
SUM(final_amount) as total_amount,
ISNULL(SUM(refund_amount), 0) AS total_refund,
SUM(final_amount) - ISNULL(SUM(refund_amount), 0) AS outstanding_amount
FROM tabel1 WHERE item_id in ('119688521',
'109536343',
'99459466',
'97126817',
'138148320',
'107816131')
GROUP BY item_id
Live demo at http://www.sqlfiddle.com/#!18/94f518/5
You are missing a comma. In addition, you should check for NULL after the SUM():
SELECT item_id,
SUM(final_amount) as total_amount,
COALESCE(SUM(refund_amount), 0) AS total_refund,
(SUM(final_amount) - COALESCE(SUM(refund_amount), 0)
) AS outstanding_amount
FROM tabel1
WHERE item_id in ('119688521', '109536343', '99459466', '97126817', '138148320', '107816131')
GROUP BY 1
Try this
SELECT item_id,
SUM(final_amount) as total_amount,
SUM(ISNULL(refund_amount, 0)) AS total_refund
SUM(final_amount - isnull(refund_amount, 0)) AS outstanding_amount
FROM tabel1 WHERE item_id in ('119688521',
'109536343',
'99459466',
'97126817',
'138148320',
'107816131')
GROUP BY item_id
Your are missing to put a comma (,) after your column ".... AS total_refund". Add the comma and this will resolve the syntax issue.
And please use GROUP BY item_id instead of GROUP BY 1
I'm working with windev using the database hyperfile client/serveur.
I have a table named Operation with colums (accountNumber, date, amount, operationType ).
operationType can take two values: "payment" and "withdrawal".
I want to select the List of operations done in an account and, my List should display 5 colums:
Date, accountNumber, amount, operationType and balance.
The last column (balance) should be the difference between the sum of all operations done before the current date with type "payment" and the sum of all operation done before the current date with type "withdrawal"
I try the following sql code
SELECT accountNumber, date as dateOpe, amount, operationType, (SUM (SELECT Operation.amount
FROM Operation
WHERE Operation.date<=dateOpe AND Operation.operationType='payment')
-SUM (SELECT Operation.amount
FROM Operation
WHERE Operation.date<=dateOpe AND Operation.operationType='withdrawal')) as balance
FROM Operation
But I always have an error telling me that i do not have the right to put a select in the SUM
Please can somebody help me. pease how can i write a such sql query.
thanks in advance
Please try this:
SELECT accountNumber, date, amount, operationType,
(SELECT SUM(amount) AS balance
FROM operation WHERE operationType='payment' and date=date)
-(SELECT SUM(amount) AS balance
FROM operation WHERE operationType='withdrawal' and date=date)
as balance
FROM operation
Try something like the following, using a subquery to find the SUMs. There may be a more elegant solution, but this should work.
SELECT date, accountNumber,
operationType, deposits - withdrawals AS balance
FROM Operations o INNER JOIN (
SELECT accountNumber, SUM(amount) AS withdrawals
FROM Operaions
WHERE operationType = 'withdrawal'
GROUP BY accountNumber
) a ON o.accountNumber = a.accountNumber
INNER JOIN (
SELECT accountNumber, SUM(amount) AS deposits
FROM Operations
WHERE operationType = 'deposit'
GROUP BY accountNumber
)b ON o.accountNumber = b.accountNumber
I would use the fact that a logical expression yields 0 if false and 1 if true. Therefore, Operation.amount * <logical expression> will yield 0 if the expression is false and Operation.amount if the expression is true. As a result, the following query should be close to a solution (untested):
SELECT accountNumber, date as dateOpe, amount, operationType,
SUM (Operation.amount * (Operation.date<=dateOpe AND Operation.operationType='payment')) -
SUM (Operation.amount * (Operation.date<=dateOpe AND Operation.operationType='withdrawal')) as balance
FROM Operation
This is the query I try to run:
Select Status from [transaction] where TransactionID IN (select MAX(CAST(TransactionID AS VARCHAR(36))), sum(debit)
FROM [transaction]
WHERE dbo.getday(StartSaleTime) >= '5/1/2011' and dbo.getday(StartSaleTime) <= '5/3/2011' and Status > -1 And TransactionNo like 'EL%' And TransactionType = 4
GROUP BY CustomerID, debit HAVING ( COUNT(CustomerID) > 1 ))
it returns this error:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
It tells you exactly what is wrong in the error message. When using in you can only specify one column in the select list.
If you change your query to this, it should work fine.
Select Status from [transaction] where TransactionID
IN (select MAX(CAST(TransactionID AS VARCHAR(36))) as [TransactionID]
FROM [transaction]
WHERE dbo.getday(StartSaleTime) >= '5/1/2011' and dbo.getday(StartSaleTime) <= '5/3/2011' and Status > -1 And TransactionNo like 'EL%' And TransactionType = 4
GROUP BY CustomerID, debit HAVING ( COUNT(CustomerID) > 1 ))
You can specify multiple columns but only when using EXISTS not IN
You are selecting two things and trying to use that with IN(). You should select only the ID when trying to do where someId In(list of Ids).
Your subquery has to return only a single field. Right now you're returning two, so the overall query looks kinda like:
SELECT ... WHERE TransactionID IN ((a,b), (c,d), etc...)
SQL server doesn't known which column to use for the IN stuff, so it's complaining.