SQL case when - create new variable - sql

**QUESTION:
Is it possible to write a SQL statement where I create a new variable 'ART2' that solves:
if holdid <> stamholdid then Art = Art where holdid = stamholdid
I guess it is some form of 'case when'-statement
I have the following SQL:**
select ua.betegnelse as ART, ut.betegnelse as TYPE, rh.stamholdnr, rh.holdnr, rh.stamholdid, rh.holdid,
rh.produkt
from rpthold rh
INNER JOIN produkt p on p.id=rh.produktid
INNER JOIN UddannelseType ut on p.UddannelsesTypeID=ut.id
INNER JOIN UddannelseArt ua on ut.UddannelseArtID=ua.id
Where
rh.stamprodukt like '3.58'
and rh.stamholdnr like '21.06%'
and Year(rh.startdato) = '2021'
Best regards
Malene

You have "case when" with if functions:
SELECT
IF (
<some_condition>,
CASE
WHEN <CONDITION>
THEN <value>
WHEN <OTHER_CONDITION>
THEN <other_value>
END,
<default_value>
) as name_field
FROM...

You can use CASE..WHEN as follows:
case when rh.stamholdid = rh.holdid then 'Art - or whatever value you need'
else 'value you want if both are not equal'
end as art2

Related

Case When + IN combination

I'm a bit stuck in my coding here... I have this extense and complex code, but I'm actually failling by the end of it. I'm getting the SQL Error [42804]: ERROR: argument of CASE/WHEN must be type boolean, not type character varying
The thing, is: when "bairro" matches a row from "SUB_COUNTRY_DB", get psd.name, else get z.name. Any tips on how I could accomplish this?
select distinct
aa.mes,
--aa.modalidade,
--to_date(aa.created_date, 'yyyy-mm-dd') data_captacao,
ucl.ja_comprou_lf as comprou_lf,
case when bairro in (select sub_country from sub_country_DB)
then psd.name
else z.name
end loja,
count (distinct aa.customer_uid) qtde_socios,
count (distinct aa.assinatura_uid) qtde_assinaturas
from assinaturas_ativas aa
left join ultima_compra_loja_fisica ucl on (aa.customer_uid = ucl.customer_uid
and aa.mes = ucl.mes)
left join zip_code z on (aa.customer_uid = z.customer_uid
and aa.mes = z.mes)
left join SUB_COUNTRY_DB psd
on (psd.district = aa.bairro)
group by 1,2,3--,4
Try variants like:
moving condition to an inner query
CASE WHEN EXISTS (SELECT DISTINCT sub_country FROM sub_country_DB WHERE sub_country = barrio)
ANY (PostgreSQL only)
CASE WHEN bairro = ANY(ARRAY_AGG(select sub_country from sub_country_DB))

Case when statement while using in join condition not working in oracle

I need to use case when on join statement in sql.I tried, but I am getting error as:
Missing expression:ORA-00905
I tried this query:
SELECT *
FROM abc a
LEFT JOIN (SELECT *
FROM anil_groups
WHERE datatype = 'C'
AND payor = 'SELECT') gr
ON CASE
WHEN Upper(a.sourcefilename) LIKE '%RIO%' THEN
gr.sourceid = 'SH_Rio_Tinto'
ELSE gr.sourceid = 'SH_Albertson'
END
LEFT JOIN (SELECT *
FROM tbl_danger
WHERE source = 'KK') spec
ON Upper(a.rollupid) = spec.code;
It doesnt work like that in oracle. CASE WHEN is a construct that provides a non boolean value, so you have to use it to run your boolean test (Upper(a.sourcefilename) LIKE '%RIO%') and have it produce the string value you want to compare to gr.sourceid:
ON gr.sourceid = CASE
WHEN Upper(a.sourcefilename) LIKE '%RIO%' THEN
'SH_Rio_Tinto'
ELSE 'SH_Albertson'
END
You can also rewrite your join not to use it:
ON (gr.sourceid = 'SH_Rio_Tinto' AND Upper(a.sourcefilename) LIKE '%RIO%') OR
(gr.sourceid = 'SH_Albertson' AND Upper(a.sourcefilename) NOT LIKE '%RIO%')

Sql Server use CONTAINS function as column in a select statement

I am writing a select statement and I would like it to include in the list of columns a call to the CONTAINS function in sql server.
I want it to be something like this:
SELECT i.IncidentID, CONTAINS(sa.AddressStreet, 'asda') AS 'asda' FROM Incident i
JOIN IncidentSubject isu ON isu.IncidentID = i.IncidentID
JOIN SubjectAddress sa ON sa.SubjectID = isu.SubjectID
WHERE i.Section <> 0 AND (i.Section & 255 <> 0)
But I get an error when using contains in the columns sections. With other functions such as LEN is works.
CONTAINS is a predicate used in the WHERE clause of a Transact-SQL SELECT statement to perform SQL Server full-text search on full-text indexed columns containing character-based data types.
It means, could not be used in SELECT.
However, as I understand correctly you can use CharIndex
SELECT i.IncidentID,
CHARINDEX('asda', sa.AddressStreet) 'asda'
FROM Incident i
JOIN IncidentSubject isu ON isu.IncidentID = i.IncidentID
JOIN SubjectAddress sa ON sa.SubjectID = isu.SubjectID
WHERE i.Section <> 0
AND (i.Section&255 <> 0);
See more on CONTAINS (Transact-SQL) and CHARINDEX (Transact-SQL)
As JohnHC already pointed out CONTAINS is a predicate that can be used in WHERE clauses only.
You could try this instead
SELECT
i.IncidentID,
CASE WHEN CHARINDEX('asda', sa.AddressStreet) > 0 THEN 'true' else 'false' end AS 'asda'
FROM Incident i
JOIN IncidentSubject isu ON isu.IncidentID = i.IncidentID
JOIN SubjectAddress sa ON sa.SubjectID = isu.SubjectID
WHERE i.Section <> 0 AND (i.Section & 255 <> 0)
Are you looking for this?
SELECT
i.IncidentID,
sa.AddressStreet [asda]
FROM Incident i
JOIN IncidentSubject isu ON isu.IncidentID = i.IncidentID
JOIN SubjectAddress sa ON sa.SubjectID = isu.SubjectID
WHERE i.Section <> 0
AND (i.Section&255 <> 0)
AND CONTAINS(sa.AddressStreet, 'asda');

case statement in where condition

In below script,it is showing 'Incorrect syntax near the keyword 'LIKE''.i am using CASE statement for checking length of F_TEXT_CODE>10. IF it is length>10 then i am using like operator if it is less than 10 i am using '=' operator.
how to achieve this logic in where condition?.
DECLARE
#MANU NVARCHAR(4000)='MANU0071'
BEGIN
SELECT TOP 1000 TP.F_PRODUCT AS ID,
TP.F_PRODUCT_NAME AS NAME
FROM PDF_DETAILS TP
LEFT JOIN V_PROD_ALIAS_MANU MAN ON MAN.F_PRODUCT = TP.F_PRODUCT
WHERE TP.F_PRODUCT<>''AND
(CASE WHEN LEN(MAN.F_TEXT_CODE)>10 THEN
(MAN.F_TEXT_CODE) LIKE #MANU
ELSE MAN.F_TEXT_CODE = #MANU END) AND
(TP.F_CUSTOM5 IS NULL OR TP.F_CUSTOM5 = '')
END
You can't use case like that.
case is an expression that returns a scalar value based on condition(s).
It can't be used as a flow-control element.
The logic you are describing can be accomplished using a combination of or and and:
DECLARE #MANU NVARCHAR(4000)='MANU0071'
BEGIN
SELECT TOP 1000 TP.F_PRODUCT AS ID,
TP.F_PRODUCT_NAME AS NAME
FROM PDF_DETAILS TP
LEFT JOIN V_PROD_ALIAS_MANU MAN ON MAN.F_PRODUCT = TP.F_PRODUCT
WHERE TP.F_PRODUCT<>''
AND
(
(LEN(MAN.F_TEXT_CODE)>10 AND MAN.F_TEXT_CODE LIKE #MANU)
OR
(LEN(MAN.F_TEXT_CODE)<=10 AND MAN.F_TEXT_CODE = #MANU)
)
AND
(TP.F_CUSTOM5 IS NULL OR TP.F_CUSTOM5 = '')
END
However, please note that using like without any wildcards will return the same result as using =, so the entire thing can be written like this
DECLARE #MANU NVARCHAR(4000)='MANU0071'
BEGIN
SELECT TOP 1000 TP.F_PRODUCT AS ID,
TP.F_PRODUCT_NAME AS NAME
FROM PDF_DETAILS TP
LEFT JOIN V_PROD_ALIAS_MANU MAN ON MAN.F_PRODUCT = TP.F_PRODUCT
WHERE TP.F_PRODUCT<>''
AND
AND MAN.F_TEXT_CODE = #MANU
AND
(TP.F_CUSTOM5 IS NULL OR TP.F_CUSTOM5 = '')
END:

How to use a non-existing column in sql query

I am working in SQL server 2012. I have to write a sql statement where I first assign a value to [Pay_Type], which is a non-existing column (not sure whether it can be called as variable or not) and based upon its value I want to use it in another case statement as shown below
SELECT sp.First_Name, [Pay_Type] = CASE WHEN NOT EXISTS(SELECT '1' FROM
PERSON_SALARY ps WHERE ps.PARTY_ID = sp.PARTY_ID and ps.END_DATE IS NULL)
THEN 'Hourly' ELSE 'Salary' END,
HOURLY_RATE = CASE WHEN [Pay_Type] = 'Hourly' THEN pj.HOURLY_RATE ELSE
'0.00' END
FROM SEC_PERSON sp
LEFT OUTER JOIN PERSON_JOB pj ON sp.PERSON_ID = pj.PERSON_ID
WHERE sp.END_DATE IS NOT NULL
But I am getting "Invalid column name 'Pay_Type' " error.
Column aliases cannot be re-used in the same SELECT where they are define. The typical answer is to use a subquery or CTE. I also like using a lateral join:
SELECT sp.First_Name, s.Pay_Type,
HOURLY_RATE = (CASE WHEN s.Pay_Type = 'Hourly' THEN pj.HOURLY_RATE ELSE
'0.00' END)
FROM SEC_PERSON sp LEFT OUTER JOIN
PERSON_JOB pj
ON sp.PERSON_ID = pj.PERSON_ID OUTER APPLY
(SELECT (CASE WHEN NOT EXISTS (SELECT 1
FROM PERSON_SALARY ps
WHERE ps.PARTY_ID = sp.PARTY_ID and ps.END_DATE IS NULL
)
THEN 'Hourly' ELSE 'Salary'
END) as PayType
) s
WHERE sp.END_DATE IS NOT NULL