Reputation: 188
I have the following schema of a table
Name Number
----- -------
A 200
A 322
B 200
B 322
C 322
C 200
D 322
D 234
I need some conditional statement to add another label column.
I want my final result to look something like this which is grouped by name.
Name Number Label
----- ------- ------
A 200 Apple
B 200 Apple
C 200 Apple
D 322 Mango
Upvotes: 0
Views: 65
Reputation: 164089
With conditional aggregation:
select
name,
case min(case number when 200 then 0 when 322 then 1 end)
when 0 then 'Apple'
when 1 then 'Mango'
end Label
from tablename
group by name
See the demo.
Results:
> name | Label
> :--- | :----
> A | Apple
> B | Apple
> C | Apple
> D | Mango
If you want the column Number
also do the aggregation inside a CTE:
with cte as (
select name, min(case number when 200 then 0 when 322 then 1 end) id
from tablename
group by name
)
select
name,
case id when 0 then 200 when 1 then 322 end Number,
case id when 0 then 'Apple' when 1 then 'Mango' end Label
from cte
See the demo.
Results:
> name | Number | Label
> :--- | -----: | :----
> A | 200 | Apple
> B | 200 | Apple
> C | 200 | Apple
> D | 322 | Mango
Upvotes: 3
Reputation: 878
You can do something like that:
SELECT (CASE WHEN [Number]=200 THEN 'APPLE' WHEN [Number] =322 THEN 'MANGO' ELSE 'WHATEVER' END) [Label], [Number]
FROM [Yourtablename]
ORDER BY (CASE WHEN [Number]=200 THEN 2 WHEN [Number] =322 THEN 1 ELSE 0 END) DESC
Upvotes: 1