unable to access case statement output from outer query. - tsql

I am trying to execute the following query in SSMS 2014. However, I am unable to access from the outer query, the column created using a case statement in the inner query. i.e.I am not able to access c.current.
Error obtained - Incorrect syntax near C
select C.trandate,C.plan,C.current from
(SELECT d.trandate,p.plan,
case when datediff(dd,trandate,getdate()) <=30 then d.amount else 0 end as 'Current',
case when datediff(dd,trandate,getdate()) between 31 and 60 then d.amount else 0 end as '31 to 60',
case when datediff(dd,trandate,getdate()) between 331 and 360 then d.amount else 0 end as '331 to 360',
case when datediff(dd,trandate,getdate()) > 360 then d.amount else 0 end as '>360',d.residentsys
FROM [HMXals_Reporting].[dbo].[TranARDetail] d
join [HMXals_Reporting].[dbo].[plans] p
on d.transys = p.plansys
) C

plan and current are both reserved keywords.
You'll have to go with
select C.trandate, C.[plan], C.[current] from
or choose other names.

Related

Is there a way to make this case statement work?

I am getting the following error with the code below:
ERROR: argument of AND must be type boolean, not type character varying
LINE 9: and case
^
SQL state: 42804
Character: 300
This code does a few things, but what I am having trouble with is the case statment. I want this piece to look for instances where the first 11 characters of two strings match. If that is not true for a given record, then look at the first 10 characters, then 9, then 8. After that, null is an acceptable result.
select cm.course_id, cm.course_name, cmp.course_id as parentcourse,
(select cmm.course_id
from course_main cmm
where cmm.course_id ilike '%Master%'
and cmm.course_id not ilike '%Ground%'
and cmm.course_id not ilike '%Surprise%'
and cmm.course_id not ilike '%emba%'
and cmm.row_status != 2
and case
when left(cm.course_id,11) = left(cmm.course_id,11)
then cmm.course_id
else
case
when left(cm.course_id,10) = left(cmm.course_id, 10)
then cmm.course_id
else
case
when left(cm.course_id,9) = left(cmm.course_id, 9)
then cmm.course_id
else
case
when left(cm.course_id,8) = left(cmm.course_id,8)
then cmm.course_id
end
end
end
end) as mastercourse
from course_main as cm
left join course_course cc
on cc.crsmain_pk1 = cm.pk1
left join course_main cmp
on cmp.pk1 = cc.crsmain_parent_pk1
where cm.course_id ilike '%-ES-2020-%'
and cm.row_status != 2
and cmp.course_id is null
order by cm.course_id;
Thank you for the assistance, Z4. I took a shot at applying your suggestions and was able to get past the error. The problem with these strings is that I am trying to match something like:
'NRSG-46009-ES-2020-OA' to 'NRSG-46009-Master-Online-Content' in an environment that also contains these:
'NRSG-46006-Master-Online-Content'
'NRSG-46003-Master-Online-Content'
'NRSG-4600-Master-Online-Content'
If I look at the first 8 characters before looking at the first 11, I will get mismatches. So, I am looking at 11 first. If there is nothing that matches, look at the first ten, and so on. Strings of 8 are the floor in our ID schema with examples like this:
'IT-7003-ES-2019-AE' that needs to be matched with 'IT-7003-Master-Online-Content'
Anyway, I took your advice and ran the following:
select distinct cm.course_id, cm.course_name, cmp.course_id as parentcourse,
case
when left(cm.course_id,11) = left(cmm.course_id,11)
then cmm.course_id
else
case
when left(cm.course_id,10) = left(cmm.course_id, 10)
then cmm.course_id
else
case
when left(cm.course_id,9) = left(cmm.course_id, 9)
then cmm.course_id
else
case
when left(cm.course_id,8) = left(cmm.course_id,8)
then cmm.course_id
end
end
end
end as mastercourse
from course_main cm
left join course_course cc
on cc.crsmain_pk1 = cm.pk1
left join course_main cmp
on cmp.pk1 = cc.crsmain_parent_pk1
left join course_main cmm
on cm.pk1 = cm.pk1
where cm.course_id ilike '%-ES-2020-%'
and cm.row_status != 2
and cmp.course_id is null
and cmm.course_id ilike '%Master%'
and cmm.course_id not ilike '%Ground%'
and cmm.course_id not ilike '%Surprise%'
and cmm.course_id not ilike '%emba%'
and cmm.row_status != 2
order by cm.course_id;
This seems to be working, but I am getting duplicate results:
results of 'successful' query
Any ideas on how I can exclude the duplicates?
First, there is really no need to use such a complex case statement. If the first 8 characters do not match, then certainly the first 9, or 10 or 11 are not going to match either, right? So just get rid of the whole thing and check only the first 8:
CASE
WHEN LEFT(cm.course_id, 8) = LEFT(cmm.course_id, 8)
THEN cmm.course_id
END
Next, the CASE statement needs to come out of the WHERE clause and into the SELECT list (this is what is causing the boolean type error):
select
[...]
(
select
CASE
WHEN LEFT(cm.course_id, 8) = LEFT(cmm.course_id, 8)
THEN cmm.course_id
END
from
course_main cmm
where
cmm.course_id ilike '%Master%'
and cmm.course_id not ilike '%Ground%'
and cmm.course_id not ilike '%Surprise%'
and cmm.course_id not ilike '%emba%'
and cmm.row_status != 2
) as mastercourse
FROM
[...]
I don't know anything about the data that you're trying to capture here, but I would also strongly suggest taking some time to rethink the use of a correlated subquery. Even if this is correctly describing the data set you want, the subquery is really inefficient. I would guess that it can probably be replaced entirely by a LEFT JOIN in the main query body (likely a self join from course_main to itself).

how can use loop or IF in case when statements in postgresql

select distinct
x.vrgid, x.Weights, x.geom
from
(select
-- postcodes.id as postcodeid ,,fishnet.geom as geom
fishnet.gid as vrgid,
fishnet.geom as geom,
CASE WHEN
st_intersects(centroids.geom, urban.geom) and counts.nonurbancells != 0
THEN 0.95 :: numeric / counts.urbancells -------1st case
WHEN st_intersects(centroids.geom, urban.geom) and counts.nonurbancells = 0
THEN 1.00 :: numeric / counts.urbancells ---2ndcase
WHEN Not st_intersects(centroids.geom, urban.geom) = fishnet.gid :: boolean and counts.nonurbancells != 0
THEN 0.05 :: numeric / counts.nonurbancells ----3rd case
ELSE 0
END AS Weights
from vrg.urban_nonurban_count_new as counts
inner join vrg.gfk_2016_id_5_digit_pcd_areas2013_projected as postcodes on postcodes.id = counts.postid
right outer join vrg.rdsid_86_quadgrid_centroids as centroids on st_contains(postcodes.geom, centroids.geom)
left outer join vrg.rdsid86_quadgrid AS fishnet on fishnet.gid = centroids.gid
right outer join vrg.rdsid86_katrisk_poly_projected as urban on st_intersects(urban.geom, fishnet.geom)
where postcodes.id = '42395') as x
I have several case statements in my PL/Pgsql function in which the I get duplicate rows (with duplicate vrgids). Below is the query result
Here (the marked row) with id 7192 is the result of 1st case statement(refer the query)
What I would like to do is use loop or if condition to remove the vrgid and corresponding weights from the result once the 1st case statement is true.
So thet I won't get duplicate records. How is it possible?
May be I should use a condition in 3rd statement to result out the vrgids not present in 1st case statement.

how do i make a grading system using cases?

pretty sure this is a pretty simple issue:
I need to create an exam results table for a student, but it needs to meet the conditions of If the student is awarded a grade of 70% or more then the result is to be shown as 'Distinction', a grade of at least 50% but less than 70% is to be shown as 'Pass' and grades below 50% are to be shown as 'Fail'. If the student has not taken the examination then the result is shown as 'Not taken'.
I'm having issues with my code which i can't seem to get right:
CREATE VIEW results_table
AS SELECT entry.excode, sname, student.sno, entry.egrade, result AS entry
FROM student
JOIN entry
ON student.sno = entry.sno
GROUP BY entry.excode, sname, student.sno, entry.egrade, result
SELECT result
CASE result
WHEN entry.egrade >= 70 THEN 'Distinction'
WHEN entry.egrade >= 50 THEN 'Pass'
WHEN entry.egrade < 50 THEN 'Fail'
WHEN entry.egrade = NULL THEN 'Not Taken'
END;
ORDER BY entry.excode,sname
could somebody please tell me where i'm going wrong?
There are two types of SQL CASE statement, as documented for PostgreSQL here:
CASE WHEN condition THEN result ELSE default END
CASE expression WHEN value THEN result ELSE default END
The first form tests a series of (unrelated) conditions, and returns the result for the first one which is true, or the ELSE if none are. The second form is a short-hand for testing multiple conditions against a single value; CASE x WHEN y THEN 'y' WHEN z THEN 'z' END is short-hand for CASE WHEN x = y THEN 'y' WHEN x = z THEN 'z' END.
In your code, you're muddling the two syntaxes; you can't use the short-hand because you're doing something more complex than = in the conditions, so you need to leave out the word result:
CASE
WHEN entry.egrade >= 70 THEN 'Distinction'
WHEN entry.egrade >= 50 THEN 'Pass'
WHEN entry.egrade < 50 THEN 'Fail'
WHEN entry.egrade IS NULL THEN 'Not Taken'
END
(Note: I've also changed = NULL to IS NULL, since no value is ever "equal to" NULL, because it means "we don't know what the value is equal to".)
You then need to put that into a SELECT query in the same place you'd select a normal column.
So starting from this simple query...
SELECT
entry.egrade as result
FROM
entry;
...you can put your CASE statement in like this:
SELECT
CASE
WHEN entry.egrade >= 70 THEN 'Distinction'
WHEN entry.egrade >= 50 THEN 'Pass'
WHEN entry.egrade < 50 THEN 'Fail'
WHEN entry.egrade IS NULL THEN 'Not Taken'
END as result
FROM
entry;

SQL query for two possible values?

I am using SSMS 2008 R2 and am trying to figure out the SQL select statement to select all records where two or more of the values are found.
These are the four possible values I am looking for. If two or more of these values (SubstanceAbuse, BehaviorEmotion, SexualAbuse, DomesticViolence) are met, I want to set a new field to 1. How do I do this?
case when qav.[test_setup_details_caption] in ('Substance Abuse / Drug Use','Caregiver monitor youth for drug alcohol use') then 1 else 0 end SubstanceAbuse,
case when qav.[test_setup_details_caption] in ('Physical Aggression','Firesetting','Gang Involvement','Runaway Behavior') then 1 else 0 end BehaviorEmotion,
case when qav.[test_setup_details_caption] = 'Problem Sexual Behavior' then 1 else 0 end SexualAbuse,
case when qav.[test_setup_details_caption] LIKE '%Domestic%' then 1 else 0 end DomesticViolence,
My suggestion would be to take the above statement and make it a virtual table in a new SELECT statement. Then you can do a SUM on the ones (since they are calculated already) in your WHERE statement and display only
where (Sub + Beh + Sex + Dom) > 1
It would look something like this (pseudo-code):
SELECT t.*
FROM (SELECT sub case, Beh case, etc.
FROM yourtable) t
WHERE (t.sub + t.Beh + t.Sex + t.Dom) > 1
It seems like all you need is this WHERE clause:
WHERE SubstanceAbuse + BehaviorEmotion + SexualAbuse + DomesticViolence > 1
update myTable set myField = 1 where 2 <= (select SubstanceAbuse + BehaviorEmotion + SexualAbuse + DomesticViolence from ...)
Of course, this is just a template for your query, but you get the idea. If the answer is still unclear then I kindly ask you to give me more details.
Best regards,
Lajos Arpad.

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.