SQL Server - Multiple SUM CASE WHEN - sql-server

First time posting so forgive me if this has been asked before.
I am not new to writing SQL but I am also no expert.
I need a better way to write this:
CASE
WHEN OrderQuantity + Week1Quantity >= CriteriaAmount THEN 1
WHEN OrderQuantity + Week1Quantity + Week2Quantity >= CriteriaAmount THEN 2
WHEN OrderQuantity + Week1Quantity + Week2Quantity + Week3Quantity >= CriteriaAmount THEN 3
WHEN OrderQuantity + Week1Quantity + Week2Quantity + Week3Quantity + Week4Quantity >= CriteriaAmount THEN 4
WHEN OrderQuantity + Week1Quantity + Week2Quantity + Week3Quantity + Week4Quantity + Week5Quantity >= CriteriaAmount THEN 5
WHEN OrderQuantity + Week1Quantity + Week2Quantity + Week3Quantity + Week4Quantity + Week5Quantity + Week6Quantity >= CriteriaAmount THEN 6
WHEN OrderQuantity + Week1Quantity + Week2Quantity + Week3Quantity + Week4Quantity + Week5Quantity + Week6Quantity + Week7Quantity > CriteriaAmount THEN 7
WHEN OrderQuantity + Week1Quantity + Week2Quantity + Week3Quantity + Week4Quantity + Week5Quantity + Week6Quantity + Week7Quantity + Week8Quantity >= CriteriaAmount THEN 8
ELSE 999
END
It's purpose is to find the first stage at which the target is hit, using numeric values from each column as a running total.
Table like so:
Order QuantityWeek 1Week 2Week 3(Suggested Target)
.........5.................5...........5...........5..................15.............
........10...............10.........10.........10.................500...........
In the above table row 1 will give an answer of 2 as there are 2 weeks to add to reach the target.
Row 2 will land on the ELSE statement giving 999 which will later be converted to an error.
I would like a better way to write this as I have 52 more columns to get through you can imagine this is a white-space-hog!
Thanks,
Adam

The design of table is very poor. After a few years it will have hundreds of columns. The only way to deal with this, if you cannot change the table design, is to use dynamic sql with exec.
The sane, and maintainable, approach is to change the table design to have one row for each item number, week number and item amount. Then you can use standard TSQL verbs such as sum and group by.

Related

Set value to 0 if it is less than zero in sql server

I have this query
SELECT
TestPackageId,
SUM(ROUND((Quantity - (QuantityBeforeDone + QuantityExistInSite + QuantitySpool + TotalMIV)), 3)) AS Shortage
FROM ...
The shortage value sometimes is negative. So if the value is negative it should be 0.
How can I do that?
A case expression is the way to go:
CASE WHEN SUM(ROUND((Quantity - (QuantityBeforeDone + QuantityExistInSite + QuantitySpool + TotalMIV)), 3)) < 0 then 0 else SUM(ROUND((Quantity - (QuantityBeforeDone + QuantityExistInSite + QuantitySpool + TotalMIV)), 3)) end
use the formula
(SUM(ROUND((
Quantity - (QuantityBeforeDone + QuantityExistInSite + QuantitySpool + TotalMIV)), 3))+
ABS(SUM(ROUND((
Quantity - (QuantityBeforeDone + QuantityExistInSite + QuantitySpool + TotalMIV)), 3)))) / 2
You need to use
Case expression
Here is an example:
case when value = 0 then 'zero' when value < 0 then 'negative' else 'positive' end
For those who prefer one short line instead of long CASE statements or duplicating value in ABS() (formula logic may change some day and need not to forget change it everywhere in code etc.).
Use isnull(nullif(sign({column name}),-1),0) :
select isnull(nullif(sign(-100),-1),0) as negative
select isnull(nullif(sign(0),-1),0) as zero
select isnull(nullif(sign(100),-1),0) as positive

Additions based on item frequency in an array (Lua)

I have an array which is used to compute a score in a game:
a = {1,7,5,1,2,6,2,3,4,5,5,6,7,7,7}
All numbers should be simply added, except when a number appears several times, for instance 7 (which appears 4 times) it should be added as such:
1*7 + 2*7 + 3*7 + 4*7
So, altogether, array "a" should give this score:
score = (1*1 + 2*1) + (1*2 + 2*2) + (1*3) + (1*4) + (1*5 + 2*5 + 3*5) + (1*6 + 2*6) + (1*7 + 2*7 + 3*7 + 4*7)
I wouldn't know where to start doing this. What's a good method for this kind of calculation?
Any help is appreciated.
You can keep track of the current multiplier for each number in another table:
function calculateScore(a)
local multipliers = {}
local score = 0
for i,number in ipairs(a) do
local multiplier = multipliers[number] or 1
multipliers[number] = multiplier + 1
score = score + number * multiplier
end
return score
end
local a = {1,7,5,1,2,6,2,3,4,5,5,6,7,7,7}
local score = calculateScore(a)

How to sum columns in SQL Server?

I am trying to create a column that is the total value of column A,B,C,D,E.
select,[TVIncome] a
,[XIncome] b
,[ZIncome] c
,[DINCOME] d
,[OIncome] e
sum(a,b,c,d,e) as total
The error I get when doing the above sum is :"The sum function requires 1 argument(s)."
The total above does not work. Also, if I just include the the proper names, XIncome and the rest,it still does not work. How do I do it?
SUM() adds each value in a column, to give a single value
+ adds each value in two columns together to give a column
It sounds like you are after a + b + c + d + e AS total,
or possibly SUM(a + b + c + d + e) AS total if you are after 1 value
Assuming you want a sum for those columns for each row
SELECT (TVIncome + XIncome + ZIncome + DIncome + OIncome) as TotalIncome
FROM Table
If you want a sum of sums, which will equal one row:
SELECT SUM(TVIncome + XIncome + ZIncome + DIncome + OIncome) as TotalIncome
FROM Table

Questions related to recursion

Please find the code below which shows some operations based on recursion.I would love some one to please explain me how this recursion works?
#include <stdio.h>
int func(int);
main()
{
int ret = 0;
ret = func(6);
printf("The val is %d\n",ret);
}
int func(int m)
{
if((m==0)||(m==1))
{
return 1;
}
else
{
return (func(m-1)+func(m-2));
}
}
When executed,the value of val is 13.Please someone explain how does this unwind operations happens in stack
You don't need to involve a stack or any unwinding (excuse me for involving myself, though).
Just substitute the call with the content of the function, and keep doing that until you no longer recurse:
ret = func(6) =
func(5) + func(4) =
func(4) + func(3) + func(3) + func(2) =
func(2) + func(3) + func(1) + func(2) + func(1) + func(2) + func(0) + func(1) =
func(0) + func(1) + func(1) + func(2) + 1 + func(0) + func(1) + 1 + func(1) + func(0) + 1 + 1 =
1 + 1 + 1 + func(0) + func(1) + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 =
3 + 1 + 1 + 8 =
3 + 2 + 8 =
13
It's a bit difficult with the typography, but that's what happens and the answer seems to match what you got, too.
Recursion is nothing more than calling the a function from within that particular function. A lot of mathematical algorithms or (tree) search algorithms use this technique for their desired result.
Recursive function calls need to 'escape' their repeating 'self calling' otherwise the application would become unresponsive. In your example, this is done by the if((m==0)||(m==1)) check. If the check is true, the function just returns 1 (and escapes the recursion).
The recursive code you showed calculates the Fibonacci sequence, which is a typical recursive algorithm, as it requires the values of 2 previous calculations. Step 0 and 1 return 1. These 2 values are added for step 2 (resulting in 1+1=2). The next step results in 1+2=3. And so on. As you see this can only be calculated from the start (and thus requires the recursion to do so)
Your program tries to print the nth(or n+1th) number of a Fibonacci series. Here the base case is when m =1 or m=0
The worst thing about recursion here is a value is calculated twice for example func(4), func(3) and func(2) as evident from here.

Difference between sp_spaceused and DataLength SQL Server

I have a table with single Row when i use SP_SpaceUsed N'<TableName>' it gives me data as 16 KB
and when I use dataLength something like this:-
select ClientID ,
(0 + isnull(datalength(ClientID), 1) +
isnull(datalength(LeadID), 1) +
isnull(datalength(Company_Name), 1) +
isnull(datalength(Website), 1) +
isnull(datalength(EmployeeCount), 1) +
isnull(datalength(Revenue), 1) +
isnull(datalength(Address), 1) +
isnull(datalength(City), 1) +
isnull(datalength(State), 1) +
isnull(datalength(ZipCode), 1) +
isnull(datalength(CountryID), 1) +
isnull(datalength(Phone), 1) +
isnull(datalength(Fax), 1) +
isnull(datalength(TimeZone), 1) +
isnull(datalength(SicNo), 1) +
isnull(datalength(SicDesc), 1) +
isnull(datalength(ResearchAnalysis), 1) +
isnull(datalength(SourceID), 1) +
isnull(datalength(BasketID), 1) +
isnull(datalength(PipelineStatusID), 1) +
isnull(datalength(SurveryID), 1) +
isnull(datalength(NextCallDt), 1) +
isnull(datalength(CurrentRecStatus), 1) +
isnull(datalength(AssignedUserID), 1) +
isnull(datalength(AssignedDate), 1) +
isnull(datalength(TotValueAmt), 1) +
isnull(datalength(Remove), 1) +
isnull(datalength(Release), 1) +
isnull(datalength(LegendID), 1) +
isnull(datalength(Inserted_Date), 1) +
isnull(datalength(Inserted_By), 1) +
isnull(datalength(Updated_Date), 1) +
isnull(datalength(Updated_By), 1))
as rowsize from TempLeadHeader order by rowsize desc
it gives rowsize 167 i guess this is in bytes
I would like to know why this difference is coming up in the result
Thanks in advance
sp_spaceused counts the space used by pages, which are 8k blocks.
Remember that a table also includes things like indexes that take up space too. not to mention that data on pages are never full unless the fill factor is 100%
datalength will tell you how many bytes your column is
you compared 1 row against a table you would have to sum it for every row and even then it won't be the same because you are not showing header information and index data
you can also do something like this
dbcc showcontig ('TempLeadHeader') with tableresults
Then look at min, max and average recordsize columns

Resources