-1

I have the following query

select  (case 
        when object like'%service%' then (object) 
        when  class like '%service%' then (class)end) From db group by (case when object like '%service%' then object
      when object_class like '%service%' then object_class end)

this query check if value of each column contains 'service' than display the data, i need instead of data only display, data and string
Some thing like when object like'%service%' then (object),'string'

String will be a variable which is stored in unknown column at results

  1. column1 column2
  2. objet1 mystring
  3. objet2 mystring
  4. objet3 mystring
Redadublex
  • 129
  • 6
  • 18

2 Answers2

2

The CASE statement only returns one value - you cannot use it to return multiple columns.

You can either repeat the case statement in each column:

select  
    case 
        when object like '%service%' then object
        when  class like '%service%' then class
    end as column1,
    case 
        when object like '%service%' then 'string'
        when  class like '%service%' then 'string'
    end as column2
FROM ...

or do a UNION:

select  
    object as column1,
    'string' as column2
WHERE object like '%service%' 
FROM ...
UNION ALL
select  
    class as column1,
    'string' as column2
WHERE class like '%service%' 
FROM ...

Note that the results will be different if there are any records where object and class both contain the string service. The UNION will return two records, the CASE will only include one (matching on object first).

D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

So in case one of the columns contains the word 'service' you display the first match as column1. And you want to display 'string' in column2 in case you display something in column1.

EDIT: I've added a GROUP BY clause on the column1, to show you how to aggregate here:

select 
  column1, 
  case when column1 is not null then 'string' end as column2,
  min(some_other_column)
from
(
  select 
    case 
      when object like '%service%' then object 
      when  class like '%service%' then class
    end as column1,
    some_other_column
  from mytable
) mydata
group by column1;
Thorsten Kettner
  • 89,309
  • 7
  • 49
  • 73