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:

  1. if name empty display_name = 'nickname'
  2. if name unique display_name = 'name'
  3. if name not_unique display_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

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -