UPDATE using case when exists ( don't get the right result) - sql

i'm trying to update a table that is alimented by 2 flows, the 1st one i have to make FillRateCode (the column i want to update) equal to FillRateCode from BWH_OTC_Order but for the 2nd flow i put it equal to '-1'
this is my script:
use BITS
;with tmp as (
select SalesOrderItemNum, SalesOrderNum, FillRateCode
From
BWH_OTC_Order
INNER JOIN REF_Company Comp
ON (Comp.CompanyCode= BWH_OTC_Order.CompanyCode AND Comp.DivisionCode='TEE')
where RevisedPGIDate is not null
)
UPDATE bits_tee.dbo.DMT_TEE_OTC_OrderFulFill
SET FillRateCode = case when exists ( select 1 from tmp) then tmp.FillRateCode else '-1' end
FROM bits_tee.dbo.DMT_TEE_OTC_OrderFulFill DMT
left outer join tmp
on tmp.SalesOrderItemNum = DMT.SalesOrderItemNum
and tmp.SalesOrderNum = DMT.SalesOrderNum
and this is the result i get
NB BWH_FillRateCode DMT_FillRateCode
124457 NULL NULL
73991 0 0
457507 1 1
28632 -1 -1
4849 2 2
34262 3 3
for nulls the correct resault is to get '-1' in DMT_FillRateCode
any issues?
Thx by advence

You can use ISNULL or COALESCE to replace NULL with something else. Your exists( select 1 from tmp) is pointless since it only checks if there are any rows (so not only related rows).
WITH tmp
AS (SELECT SalesOrderItemNum,
SalesOrderNum,
FillRateCode
FROM BWH_OTC_Order
INNER JOIN REF_Company Comp
ON ( Comp.CompanyCode = BWH_OTC_Order.CompanyCode
AND Comp.DivisionCode = 'TEE' )
WHERE RevisedPGIDate IS NOT NULL)
UPDATE DMT
SET DMT.FillRateCode = ISNULL(tmp.FillRateCode, '-1')
FROM bits_tee.dbo.DMT_TEE_OTC_OrderFulFill DMT
LEFT OUTER JOIN tmp
ON tmp.SalesOrderItemNum = DMT.SalesOrderItemNum
AND tmp.SalesOrderNum = DMT.SalesOrderNum

Maybe I'm misinterpreting your question, but if you just want to replace null values with -1 you can use the isnull function
isnull(tmp.FillRateCode,-1) -- I'm guessing the -1 is an int, and not a char '-1'
instead of
case when exists ( select 1 from tmp) then tmp.FillRateCode else '-1' end

Related

Conditionally adding a column in a SQL query

I'm trying to add a conditional SELECT column in a query and I'm having trouble writing it out:
SELECT v.GLTypeID,
v.something,
v.somethignElse,
CASE WHEN (SELECT TOP 1 Value FROM InterfaceParam WHERE InterfaceId = 0 AND Descr = 'gf') = 1 THEN a.CreditID ELSE NULL END AS CreditMemoID
FROM vGLDetails2 v
....
LEFT OUTER JOIN AssociationFund f
ON v.FundID = f.FundID
LEFT JOIN dbo.APLedger a ON v.RelID = a.APLedgerID AND v.RelTypeID IN (39, 40)
....
ORDER BY v.Code;
The query above works, however if the CASE statement is still returning an additional column regardless of the result of the subquery. How can I remove it if the subquery doesn't return a row?
How can I do this?
Change the location of AS. For example:
SELECT v.GLTypeID,
v.something,
v.somethignElse,
CASE WHEN (
SELECT TOP 1 Value
FROM InterfaceParam
WHERE InterfaceId = 0 AND Descr = 'creditMemo') = 1
THEN a.CreditID -- AS is not valid here
END AS CreditMemoID -- AS is valid here
FROM vGLDetails2 v
....
LEFT OUTER JOIN AssociationFund f
ON v.FundID = f.FundID
LEFT JOIN dbo.APLedger a ON v.RelID = a.APLedgerID AND v.RelTypeID IN (39, 40)
....
ORDER BY v.Code;
Note: I removed ELSE NULL since this is the default behavior of CASE.

How to use exists for a complete list of a product?

This is the query to find out if a particular car has W1, W2, WA, WH conditions. How can I modify my query so that I can get a list of all the cars as yes or no for these conditions?
NOTE: Here, I have put v.[carnumber] = 't8302' but I need a complete list.
SELECT
CASE
WHEN EXISTS (
SELECT co.[alias]
FROM [MTI_TAXI].[vehicle] v
LEFT JOIN [MTI_SYSTEM].[Conditions] co with (nolock) on v.DispatchSystemID = co.DispatchSystemID and (v.Conditions & co.conditionvalue > 0)
WHERE co.[alias] in ('W1', 'W2', 'WA', 'WH') and v.[DispatchSystemID] = 6 and v.[CarNumber] = 't8302')
THEN cast ('Yes' as varchar)
ELSE cast ('No' as varchar)
END AS [WATS]
OUTPUT - ( WATS - No )
But, here are all the cars but I am getting yes to WATS condition which is incorrect
enter image description here
Simply utilizing your provided filters and moving the EXISTS to be used in an OUTER APPLY statement:
SELECT
CASE
WHEN [find_wats].[Found] = 1
THEN 'Yes'
ELSE 'No'
END AS [WATS]
FROM
[MTI_TAXI].[vehicle] AS v
OUTER APPLY (SELECT TOP (1)
1 AS [Found]
FROM
[MTI_SYSTEM].[Conditions] AS co
WHERE
v.DispatchSystemID = co.DispatchSystemID
AND
(v.Conditions & co.conditionvalue > 0)
AND
co.[alias] IN ('W1', 'W2', 'WA', 'WH')
AND
v.[DispatchSystemID] = 6) AS [find_wats];
Using this set up, you can then use [find_wats].[Found] = 1 to determine that your record within the table [MTI_TAXI].[vehicle] found a match in [MTI_TAXI].[Conditions] (using your provided criteria) while still maintaining a single record in your final result set for each record originally in the table [MTI_TAXI].[vehicle].
Use count(*) to assert that there was exactly 1 row found by adding:
group by co.[alias]
having count(*) = 1
So the whole query becomes:
SELECT
CASE
WHEN EXISTS (
SELECT co.[alias]
FROM [MTI_TAXI].[vehicle] v
LEFT JOIN [MTI_SYSTEM].[Conditions] co with (nolock)
on v.DispatchSystemID = co.DispatchSystemID
and (v.Conditions & co.conditionvalue > 0)
WHERE co.[alias] in ('W1', 'W2', 'WA', 'WH')
and v.[DispatchSystemID] = 6
and v.[CarNumber] = 't8302'
group by co.[alias]
having count(*) = 1
) THEN cast ('Yes' as varchar)
ELSE cast ('No' as varchar)
end AS [WATS]

Cannot use an aggregate or a subquery

I'm trying to group this case expression but unfortunately I'm getting an error.
select da.order_id, osl.itemid, sum(case when osl.sku = '00005' then 0 when osl.sku = '00006' then 0 else osl.price * sil.quantity end) merchcost, sum(sil.merchUnitCost * sil.quantity) cogs, sum(sil.quantity) quantity,
CASE
WHEN EXISTS (SELECT * FROM fcat.dbo.subscriptionskus a where a.itemId = osl.itemid) then 1
WHEN EXISTS (SELECT * FROM foam.dbo.subscriptionprogram b where b.orderStateLineId = osl.orderStateLine_id ) then 1
else 0
END as isAdmin,
CASE
WHEN EXISTS (SELECT * FROM fcat.dbo.subscriptionskus a where a.itemId = osl.itemid) then CAST('subscriptionskus' as varchar(MAX))
WHEN EXISTS (SELECT * FROM foam.dbo.subscriptionprogram b where b.orderStateLineId = osl.orderStateLine_id ) then CAST('subscriptionprogram' as varchar(MAX))
else 'NotListed'
END as SubTable
from #dispatchAmounts da
inner join orderstates os on os.order_id = da.order_id
inner join orderstatelines osl on osl.orderState_id = os.orderState_id
inner join shippingIntentLines sil on sil.orderStateLine_id = osl.orderStateLine_id and da.shippingIntent_nbr = sil.shippingIntent_nbr
where da.code = 'merch' and sil.quantity > 0
group by da.order_id, osl.itemid, CASE
WHEN EXISTS (SELECT * FROM fcat.dbo.subscriptionskus a where a.itemId = osl.itemid) then 1
WHEN EXISTS (SELECT * FROM foam.dbo.subscriptionprogram b where b.orderStateLineId = osl.orderStateLine_id ) then 1
else 0
END,CASE
WHEN EXISTS (SELECT * FROM fcat.dbo.subscriptionskus a where a.itemId = osl.itemid) then CAST('subscriptionskus' as varchar(MAX))
WHEN EXISTS (SELECT * FROM foam.dbo.subscriptionprogram b where b.orderStateLineId = osl.orderStateLine_id ) then CAST('subscriptionprogram' as varchar(MAX))
else 'NotListed'
END
ERROR:
Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.
Is there anyway I can make this work?
I have a couple of suggestions. You are using select * in your case statements , but the columns referenced by '*' are not in your group by clause. To add them would be a bad way to fix the problem. Instead use ' select 1 ' and see what happens.
Second recommendation is to just not use the when exists rather use left join using sub queries and use those in your case statements.
So what I did is.
1. Removed the Case Statement on the Group By.
2. Modified the SubQueries on the Case Statement. Followed #Shiv Sidhu recommendation.
Thanks for everyone.

My query doesn't get the right value

My query doesn't give the right output.
I tried with different way such as with CTE as well but nothing help.
I'm trying to write View to display available products with quantity but as some data is not available in StockCloseInventory table it displaying me 0 even though records are available for some products.
Here is my query:
SELECT TOP (100) PERCENT
SOI.InStockPrdID
, SOI.ProdName
, SOI.TradeDrugId
, ISNULL(SOI.Quantity, 0) AS INQTY
, ISNULL(SCI.QuantitySold, 0) AS OUTQTY
, ISNULL(SOI.Quantity, 0) - ISNULL(SCI.QuantitySold, 0) AS AQTY
, SOI.UnitPrice
FROM dbo.StockInventory AS SOI
LEFT OUTER JOIN dbo.StockCloseInventory AS SCI
ON SOI.InStockPrdID = SCI.InStockPrdID
AND SOI.SoldOut <> 1
LEFT OUTER JOIN dbo.vwTradeDrug AS VTD
ON SOI.TradeDrugId = VTD.TradeDrugId
ORDER BY SOI.ProdName
And this is the output of my View:
And here is my Tables
Table: StockInventory
Table: StockCloseInventory
vwTradeDrug view:
CREATE VIEW [dbo].[vwTradeDrug]
AS
SELECT
T.TradeDrugId
, T.GenericDrugId
, T.TradeName
, G.GenericProprietaryName
, G.DosageType
, G.Strength
, T.TradeName + ',' + G.GenericProprietaryName + ',' + G.DosageType
+ ',' + G.Strength AS TradeFullName
FROM dbo.TradeDrug AS T
INNER JOIN Inventory.GenericDrug AS G
ON T.GenericDrugId = G.GenericId
GO
The problem is with SOI.SoldOut <> 1
First, as Pouya Kamyar pointed out, it is more conventional to include this in a WHERE clause than in a JOIN.
However, the issue is that the value of this field is mostly NULL.
What you want is something more like this:
WHERE SOI.SoldOut IS NULL
OR SOI.SoldOut <> 1
I Suggest bring "AND SOI.SoldOut <> 1" in WHERE clause not in join terms
Either change the null data in sold out to be 0 or 1 OR...
handle the nulls so that the boolean compare results in a true or false instead of "NULL" as below.
SELECT TOP (100) PERCENT
SOI.InStockPrdID
, SOI.ProdName
, SOI.TradeDrugId
, ISNULL(SOI.Quantity, 0) AS INQTY
, ISNULL(SCI.QuantitySold, 0) AS OUTQTY
, ISNULL(SOI.Quantity, 0) - ISNULL(SCI.QuantitySold, 0) AS AQTY
, SOI.UnitPrice
FROM dbo.StockInventory AS SOI
LEFT OUTER JOIN dbo.StockCloseInventory AS SCI
ON SOI.InStockPrdID = SCI.InStockPrdID
AND ISNULL(SOI.SoldOut,0) <> 1 -- this should do the trick
LEFT OUTER JOIN dbo.vwTradeDrug AS VTD
ON SOI.TradeDrugId = VTD.TradeDrugId
ORDER BY SOI.ProdName
Remember Boolean compares on Null values result in NULL (a third value in a Boolean compare!) so SOI.SoldOut <> 1 when SOI.SoldOut is null will result in NULL instead of a true/false you're expecting.

Problem with Full Outer Join not working as expected

I have a query to subtract current balance from one table with previous balance from another history table. When a particular product has no current balance but has previous balance, I am able to subtract it correctly...in this case it will be like 0 - 100.
However, when the product has current balance but no previous balance, I am unable to get the result. My query does not even select the current balance even though I have done a full outer join on both tables.
Following is my query:
SELECT DATEPART(yyyy, #ExecuteDate) * 10000 + DATEPART(mm, #ExecuteDate) * 100 + DATEPART(dd, #ExecuteDate) AS Period_Key,
CASE WHEN GL.GL_Acct_Key IS NULL THEN 0 ELSE GL.GL_Acct_Key END AS GL_Acct_Key,
CASE WHEN BANK.Bank_Type_Key IS NULL THEN 0 ELSE BANK.Bank_Type_Key END AS Bank_Type_Key,
CASE WHEN TSC.TSC_Key IS NULL THEN 0 ELSE TSC.TSC_Key END AS TSC_Key,
ISNULL(FT.CurrentBalance,0) - ISNULL(HIST.CurrentBalance,0) AS Actual_Income_Daily,
CASE WHEN BR.Branch_Key IS NULL THEN 0 ELSE BR.Branch_Key END AS Branch_Key
FROM WSB_Stage.dbo.Stage_TS_Daily_Income_Hist HIST
FULL OUTER JOIN WSB_Stage.dbo.Stage_TS_Daily_Income FT
ON FT.GLAcctID = HIST.GLAcctID AND
FT.BankType = HIST.BankType AND
FT.BranchNumber = HIST.BranchNumber
LEFT OUTER JOIN WSB_Mart.dbo.Dim_Branch BR
ON HIST.BranchNumber = BR.Branch_Code
LEFT OUTER JOIN WSB_Mart.dbo.Dim_GL_Acct GL
ON HIST.GLAcctID = GL.Acct_Code
LEFT OUTER JOIN WSB_Mart.dbo.Dim_Bank_Type BANK
ON HIST.BankType = BANK.Bank_Type_Code
LEFT OUTER JOIN WSB_Stage.dbo.Param_Branch_TSC_Map BRTSC
ON HIST.BranchNumber = BRTSC.BranchNumber
LEFT OUTER JOIN WSB_Mart.dbo.Dim_TSC TSC
ON BRTSC.RegionCode = TSC.TSC_Code
WHERE HIST.TransactionDate = #PreviousDate
AND GL.Acct_Type_Code = 'Interest'
AND BANK.Bank_Type_Key = 1
You are checking a attribute of the HIST table in the WHERE clause. If there is no entry in the HIST table, the clause doesn't match and thus discards the row.
Replace
WHERE HIST.TransactionDate = #PreviousDate
with
WHERE (HIST.TransactionDate IS NULL OR HIST.TransactionDate = #PreviousDate)
It's because of:
WHERE HIST.TransactionDate = #PreviousDate
This forces Hist.TransactionDate not to be null.
You could use
WHERE (HIST.TransactionDate = #PreviousDate OR HIST.TransactionDate IS NULL)
or change the join to:
FULL OUTER JOIN WSB_Stage.dbo.Stage_TS_Daily_Income FT
ON FT.GLAcctID = HIST.GLAcctID AND
FT.BankType = HIST.BankType AND
FT.BranchNumber = HIST.BranchNumber AND
HIST.TransactionDate = #PreviousDate
Thanks for the help but I couldn't get it to work the way I wanted using the below answers. Finally, I decided to go the long way and declare two temporary tables to hold current and previous balances. I think I want to stay as far away from outer joins as possible ;p
Code is below:
INSERT INTO #PreviousGL
SELECT GLAcctID,
BankType,
BranchNumber,
ISNULL(CurrentBalance,0) AS Current_Balance
FROM WSB_Stage.dbo.Stage_TS_Daily_Income_Hist
WHERE TransactionDate = #PreviousDate
INSERT INTO #CurrentGL
SELECT GLAcctID,
BankType,
BranchNumber,
ISNULL(CurrentBalance,0) AS Current_Balance
FROM WSB_Stage.dbo.Stage_TS_Daily_Income
INSERT INTO #DailyIncomeGL
SELECT CASE WHEN CURR.GLAcctID IS NULL THEN PREV.GLAcctID
WHEN PREV.GLAcctID IS NULL THEN CURR.GLAcctID
WHEN CURR.GLAcctID IS NULL AND PREV.GLAcctID IS NULL THEN 0
ELSE CURR.GLAcctID
END AS GLAcctID,
CASE WHEN CURR.BankType IS NULL THEN PREV.BankType
WHEN PREV.BankType IS NULL THEN CURR.BankType
WHEN CURR.BankType IS NULL AND PREV.BankType IS NULL THEN ''
ELSE CURR.BankType
END AS BankType,
CASE WHEN CURR.BranchNumber IS NULL THEN PREV.BranchNumber
WHEN PREV.BranchNumber IS NULL THEN CURR.BranchNumber
WHEN CURR.BranchNumber IS NULL AND PREV.BranchNumber IS NULL THEN 0
ELSE CURR.BranchNumber
END AS BranchNumber,
ISNULL(CURR.CurrentBal,0) - ISNULL(PREV.CurrentBal,0) AS Actual_Income_Daily
FROM #CurrentGL CURR
FULL OUTER JOIN #PreviousGL PREV
ON CURR.GLAcctID = PREV.GLAcctID AND
CURR.BankType = PREV.BankType AND
CURR.BranchNumber = PREV.BranchNumber