May 15, 2013 at 3:31 pm
I am having trouble with a CASE statement like this.
The All Cars doesn't work.
SELECT
CASE
WHEN CARS.Model LIKE '%Ford%' THEN 'Ford'
WHEN CARS.Model LIKE '%Chev%' THEN 'Chev'
WHEN CARS.Model LIKE '%Buick%' THEN 'Buick'
WHEN CARS.Model LIKE '%' THEN 'All Cars'
END AS 'Models'
May 15, 2013 at 3:36 pm
the last selection should just be an ELSE;
SELECT
CASE
WHEN CARS.Model LIKE '%Ford%' THEN 'Ford'
WHEN CARS.Model LIKE '%Chev%' THEN 'Chev'
WHEN CARS.Model LIKE '%Buick%' THEN 'Buick'
ELSE 'All Cars'
END AS 'Models'
Lowell
May 15, 2013 at 6:00 pm
The ELSE statement is not returning all models
May 16, 2013 at 12:39 am
if you want all remaining model as it is then please try this query
SELECT
CASE
WHEN CARS.Model LIKE '%Ford%' THEN 'Ford'
WHEN CARS.Model LIKE '%Chev%' THEN 'Chev'
WHEN CARS.Model LIKE '%Buick%' THEN 'Buick'
ELSE CARS.Model
END AS 'Models'
FROM CARS
May 16, 2013 at 2:30 am
Remember: if within a CASE statement the WHEN clause is TRUE, the following WHEN statements and the ELSE statement is not executed anymore.
So if some data in your example contains the value "fictive Buick Chevron" it will return "Chev" and not "Buick". Only when the data doesn't contain either "Ford" nor "Chev" nor "Buick" it will return the "All Cars" value.
May 16, 2013 at 5:43 am
I guess I have phrased my question wrong.
What I was wondering is if it is possible to use a CASE statement to return BUICK, CHEV, and then All Models (including BUICK and CHEV)
May 16, 2013 at 5:55 am
Yes, you can. In another column:
SELECT CASE
WHEN CARS.Model LIKE '%Ford%' THEN 'Ford'
WHEN CARS.Model LIKE '%Chev%' THEN 'Chev'
WHEN CARS.Model LIKE '%Buick%' THEN 'Buick'
WHEN CARS.Model LIKE '%' THEN 'All Cars'
END AS Models
,CARS.Model
FROM yourtable
or in the same column using union:
SELECT CASE
WHEN CARS.Model LIKE '%Ford%' THEN 'Ford'
WHEN CARS.Model LIKE '%Chev%' THEN 'Chev'
WHEN CARS.Model LIKE '%Buick%' THEN 'Buick'
WHEN CARS.Model LIKE '%' THEN 'All Cars'
END AS Models
FROM yourtable
UNION
SELECT CARS.Model
FROM yourtable
One more thing: do not use single quotes around column name aliases. If you really want to enclose them in something - use square brackets, otherwise you can misread them for literal strings.:
AS 'Models' - bad
AS [Models] - good
July 5, 2022 at 7:25 am
If the value "fictive Buick Chevron" is present in your example, it will return "Chev" rather than "Buick". It only returns "All Cars" if the data does not contain either "Ford" nor "Chev" nor Buick. When reading a second row from an unnested cursor, it returns -1, which is what we expect it to do here. Alternatively, may the nested cursor be utilized to run the first procedure? Any ideas you have would be greatly appreciated.
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply