Updating Sum Case Statement Grouped By Id - sql

I need to create update statement that will enable to sum converted values and write appropriate result based on case statement into database. This also must be grouped by id as we store answers that are then calculated and appropriate result must be saved to easy with analysing data.
I finally gave up after trying too many things and for today have enough. Could anyone with good heart and knowledge help please?
Below is the script I end up at the moment.
Update DB.sf_snew
Set answer =
(Case When
sum(cast(question1 as Int)) + sum(cast(question2 Int))
+ sum(cast(question3 as Int))
<= 20 Then 'reject' Else 'accept'
End
)
Group By Id
I cannot believe something that simple made my day really bad.
I appreciate any help from you.
Below is the example of data stored in a snwew table

Remove the sums and the group by:
Update DB.sf_snew
Set answer =
Case When
cast(question1 as Int) + cast(question2 Int)
+ cast(question3 as Int)
<= 20 Then 'reject' Else 'accept'
End

You don't need to use an aggregate, just do the following:
UPDATE DB.sf_snew
SET Answer = CASE WHEN CAST(Question1 AS INT) + CAST(Question2 AS INT) + CAST(Question3 AS INT) <= 20 THEN 'Reject' ELSE 'Accept' END
The UPDATE will automatically work row-by-row

Related

SQL CONCAT drops zeros from expression

I am trying different ways to put a 0 in front of month less than 10.
I tried the following expression but the 0 get dropped.
What am I doing wrong?
CASE
WHEN month([Transact_Date]) < 10
THEN CONCAT(str(0),STR(month([Transact_Date]),1))
ELSE month([Transact_Date])
END AS month_w_0
Thanks!
Tom
I think a left padding trick is what you want here. Assuming your database be SQL Server:
SELECT RIGHT('00' + STR(MONTH([Transact_Date])), 2) AS month_w_0
FROM yourTable;
You don't need a CASE expression for this. In more recent versions of SQL Server, the FORMAT function might also be able to handle this.
I have tested this and it returns the result you want:
select CASE WHEN mnt < 10 THEN
concat('0' , mnt)
ELSE mnt
END AS month_w_0
from ( select month([Transact_Date]) mnt
from test_t) A
I have realised what your problem is. YOu can do it this way too:
SELECT
CASE
WHEN month([Transact_Date]) < 10
THEN CONCAT(str(0),STR(month([Transact_Date]),1))
ELSE STR(month([Transact_Date]),1)
END AS month_w_0
from test_t
The problem is only the else part and I believe that is because case when clause returns only one type od data. In your then part you have tryed to retunr string and in the else part number.
Hope this helps...
Here is a demo

how to replace T-SQL CASE statement with efficient code

how can i replace the following case statement with efficient code
SELECT
CASE WHEN LEN(Code.Description)>=30
THEN left(Code.Description, 30) + '...'
ELSE NominalCode.Description END AS ShortDescription
FROM Code
Because the data set it returns is going to be 30-50,000 records and according to lead dev this code is ridiculous. I need help
Presumably, you intend:
SELECT (CASE WHEN LEN(c.Description) > 30
THEN left(c.Description, 30) + '...'
ELSE c.Description
END) AS ShortDescription
FROM Code c;
That is, the Description column references all come from the same table. Your code is fine.
However, I would adjust the semantics so the resulting string always has the same length:
SELECT (CASE WHEN LEN(c.Description) > 30
THEN LEFT(c.Description, 27) + '...'
ELSE c.Description
END) AS ShortDescription
FROM Code c;
Other than adding a ShortDesc field to your Product Table, perhaps I would try the following
Concat(left(Code.Description,30),IIF(Len(Code.Description)>30,'...',''))
or even
left(Code.Description,30)+IIF(Len(Code.Description)>30,'...','')
EDIT
As you can see the same execution plan, however, the performance of my approach was 18% better. This test was done on an isolated machine with a sample size of 30,000 records.

Modify int result of count in sql server 2005

I am working on sql server 2005 and I am taking count from a specific table
SELECT count(StudentIdReference) as studentCount FROM StudentTable
Right now this select statement is returning me result like 2 or 78 or 790. But in future it will grow rapidly and on UI I don't have sufficient space to show the digit like 1000000.
What I want that after 3 digit, I will get the number like 1K or 1.6K, just as we see on stackoverflow.
This would be simpler to be done in the Presentation Layer of your application.
You coud write a user function and do something like this....
CREATE FUNCTION prettyPrint
(#number int)
RETURNS varchar(30)
AS
BEGIN
declare #return varchar(30)
set #return = cast(#number as varchar(3))
if #number > 1000
set #return = ''+ cast((#number/1000) as varchar(3)) + '.' + cast((#number % 1000)/100 as varchar(3)) +'K'
-- here must be more 'exceptions' or change all this about the magic number 1000
return #return
end
select dbo.prettyPrint(1500)
SELECT prettyPrint(count(StudentIdReference)) as studentCount FROM StudentTable
As others have stated you should really be doing this in your Presentation Layer not at the DB, however, this will do it for you:
Declare #StudentCount int,
#StudentCountFormatted varchar(10)
Select #StudentCount = Count(StudentIdReference) as studentCount FROM StudentTable
If #StudentCount > 999
Begin
Select #StudentCountFormatted = Convert(Varchar(10), Convert(numeric(19,1), (#StudentCount/ 1000.00))) + 'K'
End
Else
Begin
Select #StudentCountFormatted = #StudentCount
End
Select #StudentCountFormatted
You need to write your own logic to show such text. There is no built-in method.
I would return the COUNT as-is from SQL Server and leave the formatting up to the UI. This is because:
1) usually easier/performant to do formatting/string manipulation outside of SQL
2) different places in your code using the same query may want to use the data in different ways (maybe not now, but could do in future) so returning the count as-is gives you that flexibility - i.e. won't need 1 version to return the count as an INT and another to return the same as a formatted VARCHAR
You could do it in SQL, but in general I believe in pushing this in to the UI as it's a display/formatting behaviour.
You can always try something like this
SELECT
CASE
WHEN len(cast(count(*) as varchar(10)))< 4 then cast(count(*) as varchar(10))
WHEN len(cast(count(*) as varchar(10)))> 4 and len(cast(count(*)as varchar(10)))< 7
THEN cast(cast(count(*) / 1000.0 as decimal(10,1)) as varchar(10)) + 'k'
ELSE cast(cast(count(*) / 1000000.0 as decimal(10,1)) as varchar(10)) + 'm'
END StudentCount
FROM StudentTable

A small Help needed in a _Sql Converstion of Decimal_ using **CASE**

I am need to convert a value in to decimal.Before that I am checking a condition.I want to eliminate the decimal values if #tbt=1.
Eg if #tbt=1 then 15
if #tbt=0 then 15.233
declare #tbt int =1
1) select
CASE WHEN #tbt=1 THEN CONVERT(DECIMAL(24,0),15.23335)
ELSE CONVERT(DECIMAL(24,3),15.23335) END
2) select
CASE WHEN #tbt=1 THEN '1'
ELSE '2' END
The first Query will returns 15.000.
1. Is it possible to get 15?
2. If CONVERT(DECIMAL(24,0),15.23335) returns 15.then why it is coming 15.000 in the query.
For checking I used another query and it will prints 2.
Thanks
you could use your current solution and add additional cast to Varchar(30) on both.
You can't force it to return 2 separate datatypes like this depending on the CASE.
If you insert that result into a table using SELECT INTO syntax, you'll actually see the datatype is not DECIMAL(24,0) but DECIMAL(27,3)
i.e.
declare #tbt int =1
select
CASE WHEN #tbt=1 THEN CONVERT(DECIMAL(24,0),15.23335)
ELSE CONVERT(DECIMAL(24,3),15.23335) END AS Col
INTO SomeTestTable
--Now check the SomeTestTable schema
So what SQL Server has done, is rationalised it down to a single datatype definition that can fulfil BOTH cases.
WITH T(tbt, val) AS
(
select 1,15.23335 UNION ALL
select 0,15.23335
)
Select
CASE WHEN tbt=1 THEN cast( CONVERT(DECIMAL(24,0),val) as sql_variant)
ELSE CONVERT(DECIMAL(24,3),val) END
FROM T
returns
15
15.233
Thanks to bw_üezi
I got the answer after considering his advice. thanks for all others .
Here my answer..
declare #tbt int =0
select
CASE WHEN #tbt=1 THEN CAST(CONVERT(DECIMAL(24,0),15.23335)AS NVARCHAR)
ELSE CAST(CONVERT(DECIMAL(24,3),15.23335)AS NVARCHAR) END

How do I create an If-Then-Else in T-SQL

I have some negative values coming back from a query. I would like them to just be zero.
How do I write a condition in my sql query that returns zero if the value is below a certain value.
sol:
CASE WHEN CONVERT(float,dt.FQI53X02_101) < 1.3 THEN 0 ELSE CONVERT(float,dt.FQI53X02_101) END AS FQI53X02_101
You dont use If-Then-Else in the actual query (you can use them but thats something else)...
What you use is a Case statement... Try this
Select
Case When [Value] < 0 Then 0 Else [Value] End
From
Example
If you want it as part of your query, wrap the return inside a CASE statement. Example from MSDN is below
SELECT 'Price Category' =
CASE
WHEN price IS NULL THEN 'Not yet priced'
WHEN price < 10 THEN 'Very Reasonable Title'
WHEN price >= 10 and price < 20 THEN 'Coffee Table Title'
ELSE 'Expensive book!'
END,
CAST(title AS varchar(20)) AS 'Shortened Title'
FROM titles
ORDER BY price
( ABS(Value) + Value ) / 2
edit - this doesn't work now the question has changed