sql server - SQL - Recursive conditions in SELECT clause -
i not best in sql sorry if i'm asking stupid questions :)
let's have table this:
|id| name | nickname | |==|========|============| | 1| jo| banana| | 2|margaret|the princess| | 3| perry| monkey| | 4|margaret| queen| | 5| | rat| | 6| | cat|
where nickname
unique.
and i'm trying results this:
|id| name | nickname | display_name | |==|========|============|=======================| | 1| jo| banana| jo| | 2|margaret|the princess|margaret (the princess) | 3| perry| monkey| perry| | 4|margaret| queen| margaret (the queen)| | 5| | rat| rat| | 6| | cat| cat|
basically logic is:
- if
name
emptydisplay_name = 'nickname'
- if
name
uniquedisplay_name = 'name'
- if
name
not_uniquedisplay_name = 'name (nickname)'
can achieve 1 sql query only? if - how? if not - alternatives?
currently programing language have send each row of result sql query check if there other records same name ok filtered results greedy when retrieving whole table (4 000 rows , growing).
you can use window function version of count()
determine whether name
given row unique without performing subquery. example:
select id, name, nickname, case when isnull(name, '') = '' nickname when (count(*) on (partition name)) = 1 name else name + ' (' + nickname + ')' end display_name my_table
Comments
Post a Comment