Case statement to ISNULL - tsql

I am very new to T-SQL and am looking to simplify this query using isnull.
case
when datediff(d, appdate, disdate) IS NOT NULL THEN datediff(d, appdate, disdate)
ELSE
Case
when appdate is null THEN datediff(d,update,getdate())
when disdate IS NULL THEN datediff(d,appdate,getdate())
END
END

Not much of a simplification but this should do the same thing:
ISNULL(datediff(d, appdate, disdate) ,
CASE WHEN appdate IS NULL THEN datediff(d,update,getdate())
WHEN disdate IS NULL THEN datediff(d,appdate,getdate()) END
)

Related

Postgres query how to club date and time if time is not null

with data as(SELECT c."id",c."accountId",c."name",c."campaignType",c."status",
(CASE WHEN cb."executionDetails"->>'initiatedAt' IS NULL THEN csr."startDate"
ELSE cast(cb."executionDetails"->>'initiatedAt' as TIMESTAMP)
END) as "startDate",
CASE WHEN cb."executionDetails"->>'initiatedAt' IS NOT NULL THEN NULL
ELSE csr."timeSlot"->>'type' END as "timeSlotType",
(CASE WHEN cb."executionDetails"->>'initiatedAt' IS not NULL THEN Null ELSE
-- CASE WHEN csr."timeSlotType"->>'startTime' IS NULL THEN NULL
CASE WHEN csr."timeSlot"->>'type'='MORNING' THEN '07:00'
WHEN csr."timeSlot"->>'type'='AFTERNOON' THEN '12:00'
WHEN csr."timeSlot"->>'type'='EVENING' THEN '17:00'
WHEN csr."timeSlot"->>'type'='CUSTOM' THEN (csr."timeSlot"->>'startTime')::json->>'hour'||':'||((csr."timeSlot"->>'startTime')::json->>'minute')
ELSE csr."timeSlot"->>'startTime' END END )::TIME as "startTime",
split_part(cb."batchRunId", '-',6)::decimal as batchNumber,
'CAMPAIGN' as type
FROM "Campaigns" c
LEFT JOIN "CampaignScheduleRequests" csr
ON c."id"=csr."campaignId"
LEFT JOIN "CampaignBatches" cb
ON csr."id"=cb."requestId")
SELECT * FROM data as d
WHERE d."status" IN ('ACTIVATED')
OUTPUT of the above query
Required o/p
Start time column should be concatenation of start date and startTime
with data as(
SELECT c."id",
c."accountId",
c."name",
c."campaignType",
c."status",
coalesce((cb."executionDetails"->>'initiatedAt')::timestamp,
csr."startDate")
) as "startDate",
CASE WHEN cb."executionDetails" ? 'initiatedAt' THEN NULL
ELSE csr."timeSlot"->>'type'
END as "timeSlotType",
(CASE WHEN cb."executionDetails" ? 'initiatedAt' THEN NULL
ELSE CASE csr."timeSlot"->>'type'
WHEN 'MORNING' THEN '07:00'
WHEN 'AFTERNOON' THEN '12:00'
WHEN 'EVENING' THEN '17:00'
WHEN 'CUSTOM' THEN (csr."timeSlot"->'startTime')->>'hour'
||':'
||(csr."timeSlot"->'startTime')->>'minute'
ELSE csr."timeSlot"->>'startTime' --invalid format could cause problems with ::time
END
END )::TIME as "startTime",
split_part(cb."batchRunId", '-',6)::decimal as batchNumber,
'CAMPAIGN' as type
FROM "Campaigns" c
LEFT JOIN "CampaignScheduleRequests" csr ON c."id"=csr."campaignId"
LEFT JOIN "CampaignBatches" cb ON csr."id"=cb."requestId"
WHERE c."status" IN ('ACTIVATED')
)
SELECT *,
"startDate"+coalesce("startTime",'00:00'::time) as "newStartTimestamp"
FROM data;
Use coalesce() to shorten the null replacements:
CASE WHEN cb."executionDetails"->>'initiatedAt' IS NULL
THEN csr."startDate"
ELSE cast(cb."executionDetails"->>'initiatedAt' as TIMESTAMP)
END
is the same as
coalesce((cb."executionDetails"->>'initiatedAt')::timestamp, csr."startDate")
In CASE you can do a single expression evaluation:
CASE expression
WHEN value1 THEN...
WHEN value2 THEN...
instead of a series of checks
CASE
WHEN expression=value1 THEN...
WHEN expression=value2 THEN...
Instead of casting back to json after using the ->> operator that gives you text: (jsonb->>'key1')::json->>'key2', you can just use -> to keep json output the first time.
? operator lets you check the presence of a key json?'key1' without having to check for null in an attempted read json->>'key1' is null.
You can add time to date or timestamp directly, the same how you'd add an interval. And to avoid nullifying your intitiatedAt-based startDate when adding a null-valued startTime, you can use coalesce() again - which I think was your main question.

Optimize multiple case expressions with THEN/END

I have following query.
SELECT
i.id,
CASE WHEN ia.detail_count = 1 THEN i.space_id ELSE NULL END AS space_id,
CASE WHEN ia.detail_count = 1 THEN i.resident_id ELSE NULL END AS resident_id,
CASE WHEN ia.detail_count = 1 THEN i.lease_id ELSE NULL END AS lease_id,
i.deleted_by,
i.deleted_on,
i.updated_by,
i.updated_on,
i.created_by
From
myTable i
JOIN (
SELECT
icd.id,
json_build_object(
'lease_ids', array_remove(array_agg(icd.lease_id), NULL),
'resident_ids', array_remove(array_agg(icd.resident_id), NULL),
'space_ids', array_remove(array_agg(icd.space_id), NULL)
) AS details,
COUNT(icd.id) As detail_count
FROM
mytable_details icd
GROUP BY
icd.id
) ia ON ia.id = i.id;
Can we optimize following three expressions into 1, since condition is same only operand is different.
CASE WHEN ia.detail_count = 1 THEN i.space_id ELSE NULL END AS space_id,
CASE WHEN ia.detail_count = 1 THEN i.resident_id ELSE NULL END AS resident_id,
CASE WHEN ia.detail_count = 1 THEN i.lease_id ELSE NULL END AS lease_id,
I'm not sure that this counts as an optimisation, but I think you could modify the inner query:
(COUNT(icd.id) = 1) as one_detail
... which would return a Boolean result, and then ...
case when one_detail then i.space_id end as space_id,
case when one_detail then i.resident_id end as resident_id,
case when one_detail then i.lease_id end as lease_id,
I'm not sure it's worthwhile in a simple case like this, but for a more complex condition it might be.

CREATE VIEW if 'a' not null and 'b' not null then return 'a' and 'b' else null

I am creating a view in postgres using the pgAdmin SQL window and having real trouble with the syntax for a particular part of the query.
I'd like to be able to state: where both a and b are not null then return the values for a and b, else return null.
I've started off looking at the CASE THEN ELSE statement but really can't figure this out. Any help greatly appreciated.
SELECT a, b,
CASE
WHEN a IS NOT NULL AND b IS NOT NULL
THEN a = a AND b = b
ELSE false
END
SELECT a,b,
case when a is not null and b is not null then a else null end,
case when a is not null and b is not null then b else null end

need to translate specific t-sql case in pl/sql

Can anyone tell me how to translate the following T-SQL statement:
SELECT fileld1 = CASE
WHEN T.option1 THEN -1
ELSE
CASE WHEN T.option2 THEN 0
ELSE 1
END
END
FROM Table1 AS T
The point is I need to validate two different options from the table for a single field in the select statement..
I have tried to do somthing with an IF statement in pl/sql, but it just doesnt work for me:
SELECT IF T.option1 THEN -1
ELSE IF T.option2 THEN 0
ELSE 1
END
FROM Table1 AS T
I am not actually sure how to write IF statement inside the SELECT statement..
And also, I need to do it INSIDE the select statement because I am constructing a view.
Use:
SELECT CASE
WHEN T.option1 = ? THEN -1
WHEN T.option2 = ? THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
I can't get your original TSQL to work - I get:
Msg 4145, Level 15, State 1, Line 4
An expression of non-boolean type specified in a context where a condition is expected, near 'THEN'.
...because there's no value evaluation. If you're checking if the columns are null, you'll need to use:
SELECT CASE
WHEN T.option1 IS NULL THEN -1
WHEN T.option2 IS NULL THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
...or if you need when they are not null:
SELECT CASE
WHEN T.option1 IS NOT NULL THEN -1
WHEN T.option2 IS NOT NULL THEN 0
ELSE 1
END AS field1
FROM Table1 AS T
CASE expressions shortcircuit - if the first WHEN matches, it returns the value & exits handling for that row - so the options afterwards aren't considered.
If I remember correctly, PL/SQL also supports the case. You just would have to move the column alias from "field1=" before the expression to "AS filed1" after the expression.

SELECT..CASE - Refactor T-SQL

Can I refactor the below SQL CASE statements into single for each case ?
SELECT
CASE RDV.DOMAIN_CODE WHEN 'L' THEN CN.FAMILY_NAME ELSE NULL END AS [LEGAL_FAMILY_NAME],
CASE RDV.DOMAIN_CODE WHEN 'L' THEN CN.GIVEN_NAME ELSE NULL END AS [LEGAL_GIVEN_NAME],
CASE RDV.DOMAIN_CODE WHEN 'L' THEN CN.MIDDLE_NAMES ELSE NULL END AS [LEGAL_MIDDLE_NAMES],
CASE RDV.DOMAIN_CODE WHEN 'L' THEN CN.NAME_TITLE ELSE NULL END AS [LEGAL_NAME_TITLE],
CASE RDV.DOMAIN_CODE WHEN 'P' THEN CN.FAMILY_NAME ELSE NULL END AS [PREFERRED_FAMILY_NAME],
CASE RDV.DOMAIN_CODE WHEN 'P' THEN CN.GIVEN_NAME ELSE NULL END AS [PREFERRED_GIVEN_NAME],
CASE RDV.DOMAIN_CODE WHEN 'P' THEN CN.MIDDLE_NAMES ELSE NULL END AS [PREFERRED_MIDDLE_NAMES],
CASE RDV.DOMAIN_CODE WHEN 'P' THEN CN.NAME_TITLE ELSE NULL END AS [PREFERRED_NAME_TITLE]
FROM dbo.CLIENT_NAME CN
JOIN dbo.REFERENCE_DOMAIN_VALUE RDV
ON CN.NAME_TYPE_CODE = RDV.DOMAIN_CODE AND RDV.REFERENCE_DOMAIN_ID = '7966'
No, you will require 8 separate statements as case and other such variants can only be used in a select to modify the results of a single column, not a series of columns.
If RDV.DOMAIN_COD can only by 'P' or 'L' use NULLIf. It's cleaner.
NULLIF ( expression , expression )
NULLIF is equivalent to a searched CASE expression in which the two expressions are equal and the resulting expression is NULL.
SELECT
NullIf('P', RDV.DOMAIN_CODE) AS [LEGAL_FAMILY_NAME],
...
NullIf('L', RDV.DOMAIN_CODE) AS [PREFERRED_FAMILY_NAME],
...
Since a CASE expression returns a single value, you cannot take eight CASE expressions returning 8 values and make a single CASE expression that returns all eight.
A less efficient alternative with no cases:
SELECT LEGAL_FAMILY_NAME, LEGAL_GIVEN_NAME, LEGAL_MIDDLE_NAMES, LEGAL_NAME_TITLE,
PREFERRED_FAMILY_NAME, PREFERRED_GIVEN_NAME, PREFERRED_MIDDLE_NAMES, PREFERRED_NAME_TITLE
FROM dbo.REFERENCE_DOMAIN_VALUE RDV
LEFT OUTER JOIN
( SELECT
NAME_TYPE_CODE,
FAMILY_NAME AS [LEGAL_FAMILY_NAME],
GIVEN_NAME AS [LEGAL_GIVEN_NAME],
MIDDLE_NAMES AS [LEGAL_MIDDLE_NAMES],
NAME_TITLE AS [LEGAL_NAME_TITLE]
FROM dbo.CLIENT_NAME
WHERE NAME_TYPE_CODE = 'L') LN ON RDV.DOMAIN_CODE = LN.NAME_TYPE_CODE
LEFT OUTER JOIN
( SELECT
NAME_TYPE_CODE,
FAMILY_NAME AS [PREFERRED_FAMILY_NAME],
GIVEN_NAME AS [PREFERRED_GIVEN_NAME],
MIDDLE_NAMES AS [PREFERRED_MIDDLE_NAMES],
NAME_TITLE AS [PREFERRED_NAME_TITLE]
FROM dbo.CLIENT_NAME
WHERE NAME_TYPE_CODE = 'P') PN ON RDV.DOMAIN_CODE = PN.NAME_TYPE_CODE
WHERE RDV.REFERENCE_DOMAIN_ID = '7966'
You could also use a temp table or table variable with all 8 columns and then do two inserts. You could also use a UNION ALL. My guess is that the 8 case statements are the most efficient way. This is especially true if you have some key where you will want some type of ClientID, Legal Names, Preferred Names so you will wrap a MAX around the cases or something and group by a ClientID......
You could generate the SQL script using syscols/INFORMATION_SCHEMA.columns with two case whens for each column 'CASE WHEN DOMAIN_CODE = ''P'' THEN ' + COLUMN_NAME + ' ELSE NULL END AS PREFERRED_' + COLUMN_NAME and then another for L. You could make a LOOP so that the same code executes once for P and once for L and get it down to one loop. Then you could EXEC the string directly, or PRINT it and put it into your SQL script. Anyway for just 8 columns I would cut/paste the case statements...
But anyway in general T-SQL is limited on being able to do for eaches over columns. Either you generate the script using a code generator (done in t-sql or another programming language) or you rethink your problem in another way. But many times you get better performance from duplicate cut/paste code. And many times it isn't worth the hassle of writing an external code generator (ie just for 8 case statements).