case statement in select query in sql - sql

I have a stored procedure to load the data from one table to another table.
i need to set the column value of the destination table based on the two values of the select statement, some thing like the below example.
insert into table table_name
( value1, value 2,value 3)
select (value 1,value2 ,
case value3
when value1 = 'somevalue' &&* value2 = 'somevalue'
then 'x'
else 'y'
End
from table_name.
can any one help me to find out how to update the a column in based on the two previous column values in the same select query?
i have tried with the below sample example to understand but it was failed to parse.
INSERT INTO HumanResources.departmentcopy
( DepartmentID,GroupName,Name,temp)
SELECT DepartmentID,GroupName,Name,
CASE temp
WHEN DepartmentID = 1 && Name = 'Engineering and Research'
THEN 'sucessful'
ELSE 'unsucessful'
END
FROM HumanResources.department
Help me on this!!
thanks,
Venkat

You were very close:
INSERT INTO HumanResources.departmentcopy(DepartmentID, GroupName, Name, temp)
SELECT DepartmentID,
GroupName,
Name,
CASE WHEN DepartmentID = 1 AND Name = 'Engineering and Research'
THEN 'sucessful' ELSE 'unsucessful' END
FROM HumanResources.department

&& is not valid in SQL. Use AND to append a condition.
INSERT INTO HumanResources.departmentcopy( DepartmentID,GroupName,Name,temp)
SELECT DepartmentID,
GroupName,
Name,
CASE
WHEN DepartmentID = 1 AND Name = 'Engineering and Research' THEN 'sucessful'
ELSE 'unsucessful'
END
FROM HumanResources.department

INSERT INTO HumanResources.department(DepartmentID, GroupName, Name, temp)
SELECT DepartmentID,
GroupName,
Name,
CASE WHEN DepartmentID = 1 AND Name = 'Engineering and Research'
THEN 'sucessful' ELSE 'unsucessful' END
FROM HumanResources.department

Related

SQL Select a specific value in the group

I have this following table
Dept---------- Sub_Dept---- Dept Type
Sales.............Advertising........A
Sales.............Marketing......... B
Sales.............Analytics.......... C
Operations.....IT..................... C
Operations.....Settlement........C
And the result should be if a department got a department type as A then change all record of that department to A, else keep it same
Dept---------- Sub_Dept---- Dept Type
Sales.............Advertising........A
Sales.............Marketing......... A
Sales.............Analytics.......... A
Operations.....IT..................... C
Operations.....Settlement........C
Anybody can give a suggestion on this? I thought of using the GROUP BY but have to output the Sub Department as well
Thanks a lot
I would do:
update t
set depttype = 'a'
where exists (select 1 from t t2 where t2.dept = t.dept and t2.dept = 'a') and
t.dept <> 'a';
If you just want a select, then do:
select t.*,
(case when sum(case when depttype = 'a' then 1 else 0 end) over (partition by dept) > 1
then 'a'
else depttype
end) as new_depttype
from t;
Use below query
select a11.dept, a12.Sub_Dept, (case when a12.min_dep_type='A' then 'A' else a11.dep_type) as dep_type
from tab a11
JOIN (select dept, min(dep_type) min_dep_type from tab group by dept) a12
on a11.dept = a12.dept
Try this:
update table
set depttype= case when dept in (select dept from table where depttype='a') then 'a' else depttype end
This should work:
select a.dept, a.sub_dept,
case when b.dept is not null then 'A' else dept_type end as dept_type
from aTable a
left join(
select distinct Dept from aTable where dept_type = 'A'
)
b on b.dept = a.dept
You could use analytic functions to check whether exists the specific value in the group.
Try below query:
SELECT t.Dept,
t.Sub_Dept,
NVL(MIN(CASE WHEN t.Dept_Type = 'A'
THEN Dept_Type END) OVER (PARTITION BY t.Dept), t.Dept_Type) AS Dept_Type
FROM table_1 t
Using the analytic function MIN(), you can search for the value of 'A' (if it does exist inside the group). MIN works for non-null values only, so if you don't have any 'A' in the group, the result will be NULL.
At this point, you can use NVL to choose whether to print the value found in the group or the actual dept_type of the row.

Use generated column to create another column - SQL Server

I have a column that gets generated using CAST(CASE WHEN A and B THEN SSS) as Name
Now I need another column which will use the value of the column above in the same way (CASE WHEN Name SSS THEN 123)
Is that possible?
UPDATE:
Example:
I have a table with
Name, Age, UserCode, UserId
I would like to generate a table using SELECT which includes
Name, UserCode, UserName
Name: returned from the column Name
UserCode:
CAST(CASE WHEN UserCode = 'A' and UserId = 'B' THEN 'SSS'
CASE WHEN UserCode = 'C' and UserId = 'Z' THEN 'ZAZ')
UserName: use the result from UserCode, so if UserCode is SSS then UserName become SAR123 etc...
Try this:
Select *,
CASE UserCode
When 'SSS' Then 'SAR123'
--When ... --<<Put other When clauses here
END AS UserName
FROM(
Select Name ,
CASE WHEN UserCode = 'A' and UserId = 'B' THEN 'SSS'
WHEN UserCode = 'C' and UserId = 'Z' THEN 'ZAZ'
END AS UserCode
From Table
) AS K
The alias of column name are obtained after the FROM, WHERE and then SELECT clause code evaluation .. so these alias are not available before this evalution is finished for this reason
alias of column name are not allowed in select or where clause and for these clause you must rewrite the code when need
select (CASE WHEN CAST(CASE WHEN A and B THEN SSS .....) SSS THEN 123 .... )
FROM my_table
.......
but alias for column name are available for ORDER BY and GROUP BY (clause that are evalueted after the previous mentioned)
alias of coulmn can be used in order by and group by

Conditionally select value of a column based on another column

I have a query that at high level is something like this:
Select SomeColumns, LastName, StartDateString
from MyTable
Is it possible to have a logic in this select statement that can say print for value of "StartDateString" column the "not started" if LastName is for example "abcd". and print its real value otherwise.
Basically I want to know how to write a logic for output of one column based on value of some other column in the same row. ( I am using SQL Server )
You can use CASE.
SELECT
SomeColumns,
LastName,
CASE WHEN LastName = 'abcd' THEN 'Not Started'
ELSE StartDateString END AS StartDateString
FROM MyTable
Select SomeColumns, LastName, StartDateString ,(case when Lastname = 'abcd'+
then 'not started' else 'started' +'on' + cast (StartDateString as varchar) end) as NewColumn
from MyTable

How best to Count(*) with a CASE STATEMENT?

The following SQL (on SQL Server) returns an error of:
Incorrect syntax near '*'
Is there something inherently wrong with using the following SELECT statement?:
SELECT
COUNT(CASE WHEN <conditions> THEN * ELSE NULL END) as conditionalcountall
FROM TABLE
I tried this variation which also failed:
SELECT
CASE WHEN <conditions> THEN COUNT(*) ELSE NULL END as conditionalcountall
FROM TABLE
I tend to like sum()
SELECT
SUM(CASE WHEN <conditions> THEN 1 ELSE 0 END) as conditionalcountall
FROM TABLE
Try This, it is Tested
SELECT
CASE WHEN 1 = 1 THEN COUNT(*) ELSE NULL END as conditionalcountall
FROM TABLE
1 = 1is example conditions
Demo:-
Create table #temp (id int , col1 varchar (10))
go
insert into #temp values (1 , 'aaaa')
insert into #temp values (2 , 'bbbb')
insert into #temp values (3 , 'cccc')
SELECT
CASE WHEN 1 = 1 THEN COUNT(*) ELSE NULL END as conditionalcountall
FROM #temp
Result:
In Case Condation like that id = 1 you should select Count(*) in CASE cluse in your query
like this:
SELECT
CASE WHEN id = 1 THEN (select COUNT(*) from #temp) ELSE NULL END as conditionalcountall
FROM #temp
Result:-
Note: if You used Count(*) directly, you counted the id column, so you should use group by as next:
SELECT
CASE WHEN id = 1 THEN COUNT(*) ELSE NULL END as conditionalcountall
FROM #temp
group by id
Result:
SELECT
CASE WHEN X THEN Y
ELSE Z
END *NEW COLUMN NAME*
, COUNT(*)
FROM
TABLE
GROUP BY
*NEW COLUMN NAME*
This should return two columns, one with the buckets/case statement and one with the count of the columns for each one of your buckets
This method was the most straightforward for myself
If you REALLY, REALLY want to use COUNT, then you can do this:
SELECT
COUNT(*)
FROM table
WHERE <conditions>

Selecting Columns Based on Case or If Statements

I wan't to display columns based on conditions/parameters
what i want is
if(#SelectFlag==true)
select name,Address,salary,CreatedBy from employee
else (#UpdateFlag==true)
select name,Address,salary from employee
-- in this case i don't require the column "CreatedBy"
How can i make a query or stored procedure looking at the above circumstances..
Thanks & regards..
Use single = and 1 instead of true.
if #SelectFlag = 1
select name, Address, salary, CreatedBy from employee
else
if #UpdateFlag = 1
select name, Address, salary from employee
here's an example for creating stored procedure, maybe you need to have only one parameter that indicates what are you trying to do
CREATE PROCEDURE procedurenameHere(#EventFlag INTEGER)
AS
-- #EventFlag
-- 1 for SELECT
-- 2 for UPDATE
IF #EventFlag = 1
SELECT name,Address,salary,CreatedBy
FROM employee
ELSE IF #EventFlag = 2
SELECT name,Address,salary, NULL AS CreatedBy
FROM employee
GO
execution:
EXEC procedurenameHere 1
Try this
Table : emp
Columns : name, address, salary, creditedBy
declare My_Block
p_select_flag emp.SelectFlag%type;
p_updateFlag emp.UpdateFlag%type;
BEGIN
select selectFlag into p_select_flag from emp where name='ASIF';
select update into p_updateFlag from emp where name='ASIF';
IF p_select_flag = 'TRUE' THEN
select name,Address,salary,CreatedBy from employee;
ELSIF UpdateFlag = 'TRUE' then
select name,Address,salary from employee;
END IF;
END My_Block
U can call inside the SP with parameter and pass one parameter as FLAG as Integer:
Use single = and 1,2 instead of true.
1 INDICATE FOR SELECT AND 2 INDICATE FOR UPDATE
if #FLAG = 1
select name, Address, salary, CreatedBy from employee
else
if #FLAG = 2
select name, Address, salary from employee