i want to write nested case when condition in query to store the value that will come from one case when condition and another case when condition into same new column.to get this kind of result i am writing the query as:
(case when sq_name_new1 like format('%%%s%%',demo.name) THEN count(sq_name_new1) else (when demo.empcode is not null then count(demo.id) End) END) AS indivisual from res_scheduledjobs
in the above query demo.name column comes from CTE.so my whole query look like:
with demo(empcode,id,name) as
(select hr_employee.emp_code,hr_employee.id,concat(resource_resource.name,' ',hr_employee.middle_name,' ',hr_employee.last_name) as name from hr_employee inner join resource_resource on resource_resource.id=hr_employee.resource_id)
select demo.empcode,demo.name,sq_name_new1,(case when sq_name_new1 like format('%%%s%%',demo.name) THEN count(sq_name_new1) else (when demo.empcode is not null then count(demo.id) End) END) AS indivisual from res_scheduledjobs LEFT JOIN demo on demo.id=res_scheduledjobs.assigned_technician group by res_scheduledjobs.assigned_technician,sq_name_new1,demo.empcode,demo.name ;
i just want to store the count of (sq_name_new1) column into INDIVISUAL Column and the count of (demo.id) column into same column,that is in INDIVISUAL,if the first case condition does not match.
but when i am executing my query it throw an error.that is,something is wrong in the syntax of case when condition.
please help me yo write the correct nested case-when condition.
CASE ... WHEN ... END is an expression. It can be nested like any other expression.
CASE
WHEN condition THEN
CASE
WHEN othercondition THEN
....
END
END
The first semicolon ; should be removed as in #Craig Ringer's answer.
SELECT
CASE WHEN condition1 THEN
CASE
WHEN condition1.1 THEN
...
END
END AS column_name
FROM table_name;
Related
I need to create a function that returns the string 'fall' or 'spring' depending on the month of the year. If the function was named getterm and took no parameters I would like to use it in a select statement like this:
select name, classname, getterm from classtable
where classtable holds the names of the classes we offer. The result set would include the columns as follows:
-Jack, Data Systems, Sp2022
-Jill, Web Stuff, F2023
I have used the now() function. I can also use extract(quarter from now()) to get my current quarter. It would seem simple then to use an 'if' or 'case' clause to return 'spring' or 'fall' based upon the quarters. I just haven't found any examples of a function like this.
Can anyone suggest some sample code ?
Per documentation from here CASE:
There is a “simple” form of CASE expression that is a variant of the general form above:
CASE expression
WHEN value THEN result
[WHEN ...]
[ELSE result]
END
The first expression is computed, then compared to each of the value expressions in the WHEN clauses until one is found that is equal to it. If no match is found, the result of the ELSE clause (or a null value) is returned. This is similar to the switch statement in C.
This translates in your case to:
SELECT
CASE extract('quarter' FROM now())
WHEN 1 THEN
'winter'
WHEN 2 THEN
'spring'
WHEN 3 THEN
'summer'
WHEN 4 THEN
'fall'
END;
case
--------
spring
Thank you to Adrian.. I now have the working function:
create function getTermString() returns text as $$
select case extract(quarter from now())
when 1 then 'sp'
when 2 then 'sp'
when 3 then 'f'
when 4 then 'f'
end ;
$$ language SQL;
I have a subquery like this
with subquery as (select host from table_A where << some condition >>)
and in my main query, I am querying data from another table called table_B, and one of the columns is called destination_host. Now I need to check if the destination_host is in the list returned from my subquery, then I want to output TypeA in my select statement or else TypeB. My select statement looks something like
select name, place, destination_host
from table_B
where <<some condition>>
I want to output a fourth column that is based on a condition check, let's say we call this host_category and if the destination_host value exists in the subquery then I want to add value typeA or else typeB. Please can you help me understand how to write this. I understand that it is hard to provide guidance if you don't have actual data to work with.
I tried using case statements such as this one:
when (destination_host in (select host from subquery)) THEN 'typeA'
when (destination_host not in (select host from subquery)) THEN 'typeB'
end as host_category
but I don't think this is the way to solve this problem.
I would use EXISTS:
WITH subquery AS (...)
SELECT CASE WHEN EXISTS (SELECT 1 FROM subquery
WHERE subquery.host = table_b.destination_host)
THEN 'typeA'
ELSE 'typeB'
END
FROM table_b;
With queries like that, you have to take care of NULL values. If table_b.destination_host is NULL, the row will always show up as typeB, because NULL = NULL is not TRUE in SQL.
Is there a way in T-SQL to collect all not contemplated values in a CASE condition and insert them in a table?
For example:
A SELECT that reads a table that has in Col1 the values A,B,C. This SELECT has a CASE that goes like this: CASE WHEN Col1 = 1 THEN ... WHEN Col1 = B THEN ... ELSE NULL END AS NewCol1
I would like to detect values like C, values that are not contemplated in Col1.
I could get them like this: (...) ELSE Tabl1.Col1 but I need the CASE statement to end with ELSE NULL.
You can get a list of these values like this:
SELECT DISTINCT Col1
FROM Table
WHERE Col1 not in (1,...,B)
As #avery_larry suggested, I used a debug flag, giving my query two behaviours. I could call a function/stored with the parameter and if it's up INSERT the values into a desired output.
I need to further refine my stored proc resultset from this post, I need to filter my resultset to display only records where emailaddr is NULL (meaning display only records that have Invoice_DeliveryType value of 'N' ).
Among numerous queries, I have tried:
select
Invoice_ID, 'Unknown' as Invoice_Status,
case when Invoice_Printed is null then '' else 'Y' end as Invoice_Printed,
case when Invoice_DeliveryDate is null then '' else 'Y' end as Invoice_Delivered,
(case when Invoice_DeliveryType <> 'USPS' then ''
when exists (Select 1
from dbo.Client c
Where c.Client_ID = SUBSTRING(i.Invoice_ID, 1, 6) and
c.emailaddr is not null
)
then 'Y'
else 'N'
end)
Invoice_ContactLName + ', ' + Invoice_ContactFName as ContactName,
from
dbo.Invoice
left outer join
dbo.fnInvoiceCurrentStatus() on Invoice_ID = CUST_InvoiceID
where
CUST_StatusID = 7
AND Invoice_ID = dbo.Client.Client_ID
AND dbo.client.emailaddr is NULL
order by
Inv_Created
but I get an error
The conversion of the nvarchar value '20111028995999' overflowed an int column
How can I get the stored procedure to only return records with DeliveryType = 'N' ?
Trying selecting the stored proc results into a temp table, then select
* from #TempTable
We could really do with a schema definition to get this problem resolved.
It appears that there is an implicit conversion occurring within one of your case statements, but without the schema def's it's difficult to track down which one.
You can't safely mix datatypes in CASE expressions, unless you are absolutely sure that any implicit conversions will work out OK you should make the conversions explicit.
Judging by the error message seeming to include something that could be a date represented as a string(20111028) plus some kind of other data ?time?(995999) it may be something to do with Invoice_DeliveryDate, but this is a shot in the dark without more details.
I have written a recursive function and depending on the output I need to select different fields. My question is now, how can I do this multiple times without having to call the function more then once? What I'm doing right now is just using the CASE WHEN... condition and checking every time what the functions return. (This is only a pseudo code and doesn't do anything real, it's just for understanding)
SELECT
id,
(CASE WHEN (function(id) > 0)
THEN field1
ELSE field2
END) as value1,
(CASE WHEN (function(id) > 0)
THEN field3
ELSE field4
END) as value2,
(CASE WHEN (function(id) > 0)
THEN field5
ELSE field6
END) as value3
FROM table1
...
How can I optimize this query and call the function only once?
Thanks in advance!
If the function is declared IMMUTABLE, it is safe to call it many times, as it will not be reevaluated.
From the docs:
IMMUTABLE indicates that the function cannot modify the database and always returns the same result when given the same argument values; that is, it does not do database lookups or otherwise use information not directly present in its argument list. If this option is given, any call of the function with all-constant arguments can be immediately replaced with the function value.
use a subquery :
SELECT foo, bar, result
FROM (
SELECT ..., function(id) AS result
....
) as tmp
You may be able to use some funky tuple thing like:
SELECT id,
CASE WHEN function(id) > 0
THEN (field1, field3, field5)
ELSE (field2, field4, field6)
END as (value1, value2, value3)
but I have no experience with this syntax