SQL inline variable assignment - sql

I have a SQL statement that determines the number of days between two dates. If the difference is negative, the statement needs to select 0. This statement works but I was wondering if it is possible to assign the value of datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) to a # variable so I don't have to call it twice.
SELECT CASE
WHEN datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) < 0 THEN 0
ELSE datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate)
END from ...
Please don't ask why I am calculating this value using SQL instead of in code.
Thanks

You could move the case statement inside the calculation, like this:
Select DateDiff("D", GetDate(), Case When YourColumn > GetDate()
Then YourColumn
Else GetDate()
End)

You can write a higher level SELECT something like this.
SELECT CASE
WHEN diff_date < 0 THEN 0
ELSE diff_date
END
FROM (
SELECT datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) AS diff_date
from ...
)

If you are selecting more than one row, then you can't assign it to a variable. In your case, you can use a derived table or a CTE:
SELECT Cols,
CASE
WHEN DiffDates < 0 THEN 0
ELSE DiffDates
END DiffDates
FROM ( SELECT Cols, datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) DiffDates
FROM dbo.tblKBX_Reward) A
Or:
;WITH CTE AS
(
SELECT Cols, datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) DiffDates
FROM dbo.tblKBX_Reward
)
SELECT Cols,
CASE
WHEN DiffDates < 0 THEN 0
ELSE DiffDates
END DiffDates
FROM CTE

SELECT
CASE WHEN daydiff < 0 THEN 0 ELSE daydiff END
FROM your tables/joins
CROSS APPLY (
SELECT DATEDIFF(DAY, GETDATE(), dbo.tblKBX_Reward.validdate)
) x (daydiff)
WHERE …

You could use a CTE:
WITH cte_dateDiffs (RewardId, dateDiff)
AS (
SELECT RewardId, datediff("D",GETDATE(), validdate) FROM dbo.tblKBX_Reward
)
SELECT CASE
WHEN dd.dateDiff < 0 THEN 0
ELSE dd.dateDiff
END
FROM dbo.tblKBX_Reward r
INNER JOIN cte_dateDiffs dd ON r.RewardId == dd.RewardId
...

Related

Nested case statement - what's is wrong with it?

I want to write a nested case statement where i want in Microsoft SQL Server that
case
when date 2 is null
then date 1
else date 2
end ---1st condition
and use this condition as:
case
when condition1 is <= getdate()
and condition1 < getdate() + 14
then 'DUE'
else 'after .
I am getting error message and not able to complete my case statement.
you don't need the 1st check because both the checks are comparing getdate
case when isnull([date 1],[date 2]) <= getdate() + 14 then 'DUE' else <'' end
I would use CROSS APPLY for this :
SELECT t2.y
FROM sometable
CROSS APPLY (SELECT CASE WHEN date 2 IS NULL THEN date 1 ELSE date 2 END) t1(x)
CROSS APPLY (SELECT CASE WHEN t1.x <= getdate() AND t1.x < getdate() + 14 THEN 'DUE' ELSE 'AFTER' END) t2(y)
Note that you can use COALESCE to make the first CROSS APPLY expression simpler, and IIF for the second :
SELECT t2.y
FROM sometable
CROSS APPLY (SELECT COALESCE(date 2, date 1)) t1(x)
CROSS APPLY (SELECT IIF(t1.x <= getdate() AND t1.x < getdate() + 14, 'DUE', 'AFTER')) t2(y)

Complex Query SQL

I am currently working on an sql query where i am receiving data in three different rows, i really need the data in one single row
SELECT
substring(D.F1056, patindex('%[^0]%',D.F1056), 10) as Shop_Number,
REPLACE(CONVERT(VARCHAR(10), D.F254, 103), '/', '') AS Todays_Date,
SDP_TAB.F03 as Rayon,
[SDP_TAB].F04 as Famille,
CASE
WHEN D.F1034=3 THEN SUM(D.F64)
ELSE 0
END as Qty_Sold ,
CASE
WHEN D.F1034=3 THEN convert(DOUBLE PRECISION, SUM(D.F65)*100) * 10
ELSE 0
END as chiffre_daffaire_Caisse,
0 as montant_remisse_caisse,
CASE
WHEN D.F1034=3011 THEN SUM(D.F64)
WHEN D.F1034=3012 THEN SUM(D.F64)
ELSE 0
END as Qty_retour,
CASE
WHEN D.F1034=3011 THEN SUM(D.F65)
WHEN D.F1034=3012 THEN SUM(D.F65)
ELSE 0
END as Montant_Retour,
0 as Quantity,
CASE
WHEN D.F1034=3102 THEN SUM(D.F64)
ELSE 0
END as ClientCount,
F1034
FROM
[dbo].[RPT_ITM_D] D
LEFT OUTER JOIN [dbo].[POS_TAB] ON (D.F01=POS_TAB.F01)
LEFT OUTER JOIN [dbo].SDP_TAB ON (POS_TAB.F04=SDP_TAB.F04)
where
D.F1034 IN (3,3012,3011,3102)
AND
D.F254 = convert(varchar, getdate(), 101)
group by D.F1056,D.F254,SDP_TAB.F03,SDP_TAB.F04,D.F1034
My data is being populated as below
I am having three rows since i am having several condition for field F1034
Is there a way to have the expected result as below
Try this. (Using max with calculated columns)
With resultData as (
—Put your original query here
)
Select Shop_Number, Todays_Date,rayon,famille
,max(Qty_Sold) Qty_Sold, max(chiffre_daffaire_Caisse) chiffre_daffaire_Caisse
,max(montant_remisse_caisse) montant_remisse_caisse,max(Qty_retour) Qty_retour,max(Montant_Retour) Montant_Retour
,max(Quantity)Quantity,max(ClientCount) ClientCount,max(F1034) F1034
From resultData
group by Shop_Number, Todays_Date,rayon,famille

SQL - Sum of positive and negative numbers using subquery

I have a table which contains positive and negative numbers. I have to find out sum of positive and negative numbers using sub query
Your question isn't very clear (no table nor column names given), nor is it clear why you need a subquery (never a good idea if it can be avoided). You can get the values that you want by use of the 'case' statement
The following counts the number of positive and negative values
select sum (case when acolumn >= 0 then 1 else 0 end) as positive,
sum (case when acolumn < 0 then 1 else 0 end) as negative
from table
whereas the following sums the number of positive and negative values
select sum (case when acolumn >= 0 then acolumn else 0 end) as positive,
sum (case when acolumn < 0 then acolumn else 0 end) as negative
from table
For the sum of the negative :
SELECT SUM(numberColumn) FROM tableFoo WHERE numberColumn < 0
For the sum of the positive:
SELECT SUM(numberColumn) FROM tableFoo WHERE numberColumn >= 0
To combine the two (with QUERY1 and QUERY2 being the two previous queries):
SELECT (QUERY1), (QUERY2)
select sum(case when a>=0 then a else 0 end) as positive,
sum(case when a<0 then a else 0 end) as negative
from a
By using CTE(Common table Expression) we can get the output.
;WITH Psum_CTE
AS
( SELECT SUM(num) AS PositiveSum
FROM sample
WHERE num>=0
)
,Nsum_CTE
AS
(
SELECT SUM(num) AS NegativeSum
FROM sample
WHERE num<0
)
SELECT PositiveSum,NegativeSum
FROM Psum_CTE,Nsum_CTE
SELECT (
(SELECT SUM(numberColumn) FROM tableFoo WHERE numberColumn < 0 ) -
(SELECT SUM(numberColumn) FROM tableFoo WHERE numberColumn > 0)
) AS totalCalculation
You can use sign to separate the values:
select Sum( ( Sign( n ) + 1 ) / 2 * n ) as PositiveSum,
Sum( -( Sign( n ) - 1 ) / 2 * n ) as NegativeSum
from YourTableOData;
Sign returns 1, 0 or -1 depending on the sign of the input value. A little arithmetic can convert that into 1 or 0 depending on the sign: ( Sign( n ) + 1 ) / 2 is 1 for all positive values, otherwise 0. Note that the check for negative values (( Sign( n ) - 1 ) / 2) returns -1 or 0, hence the negation (-) to avoid flipping the sign of the value that is being summed.

SUM field not summing

Similar to my last question. Heres my code:
SELECT TR.ITEMNO,
SUM ( TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'PO' THEN 1 ELSE 0 END ) AS SUM_IN,
SUM ( TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'MH' THEN 1 ELSE 0 END ) AS SUM_OUT
FROM IQMS.TRANSLOG TR
WHERE TR.ITEMNO = '200672'
GROUP BY TR.ITEMNO
HAVING SUM ( TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'PO' THEN 1 ELSE -1 END ) < 0
ORDER BY TR.ITEMNO
The code is running fine but it is not summing anything for SUM_OUT. I know for a fact however that there are numbers there to be summed. Is there something obvious that I am missing? Thanks in advance!! :)
Try...
SUM (TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'PO' THEN 1 ELSE 0 END )
OVER(PARTITION BY TR.ITEMNO) AS SUM_IN,
SUM ( TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'MH' THEN 1 ELSE 0 END )
OVER(PARTITION BY TR.ITEMNO) AS SUM_OUT,

inserting if in a select query

How can i do something like this ?
SELECT (IF(SUM(Costo) > 0) SUM(Costo) ELSE 0) AS Expr1
FROM TDP_NotaSpeseSezB
You want to use a CASE statement.
Select
CASE WHEN SUM(Costo) > 0 THEN SUM(Costo)
ELSE 0
END 'Expr1'
FROM
TDP_NotaSpeseSezB
You can use case statement like this:
SELECT case when sum(Costo)> 0 then sum(Costo)
else 0 end as Expr1
FROM TDP_NotaSpeseSezB
CASE (Transact-SQL)
SELECT CASE WHEN SUM(Costo) > 0 THEN SUM(Costo) ELSE 0 END AS Expr1
FROM TDP_NotaSpeseSezB
Other major engines support this syntax:
SELECT GREATEST(SUM(Costo), 0)
FROM TDP_NotaSpeseSezB
SQL Server, however, does not.