Refactoring T-SQL nested SELECT query to use in a case statement

I have the following table:

maker   model   type
B   1121    pc
A   1233    pc
E   1260    pc
A   1752    laptop
A   1276    printer
D   1288    printer

I need to receive a result in the form: maker, pc. If a particular maker has models in a given type, I need to concatenate the word 'yes' with the number of models in parentheses. Ex. yes(1) for maker 'A'. So, how can I avoid the following duplication?

CASE 
WHEN SELECT COUNT(*) WHERE ... > 0
THEN 'yes(' + CAST((SELECT COUNT(*) WHERE ...) AS varchar) + ')'

This is not a real world problem. I just need to understand how to save a subquery result to use it in a branch statement. The result of this branch statement may contain the subquery result itself.

Upvotes: 2

Views: 561

Answers (1)

dani herrera
dani herrera

Reputation: 51705

Creating tables:

create table #t (maker varchar(100), model  varchar(100), type varchar(100) );
insert into #t ( maker,   model,   type )  values 
( 'B',   '1121',    'pc'),
( 'A',   '1233',    'pc'),
( 'E',   '1260',    'pc');

Query in easy steps:

;with 
totals as (
   select maker, type,
       count( * ) as n
   from
       #t
   group by 
      maker,  type
      ) ,
maker_type as (
   select distinct maker, type
   from #t
)
select 
   mm.*, t.n, 
   case  when t.n is null then 'No' else 'Yes' end as yes_no
from
   maker_type mm
left outer join
   totals t
      on mm.maker = t.maker and
         mm.type = t.type

Results:

maker type n yes_no 
----- ---- - ------ 
A     pc   1 Yes    
B     pc   1 Yes    
E     pc   1 Yes 

I don't extend solution concatenating strings because I see that you know how to do it. Be free to change first or second CTE query to match yours requirements.

Upvotes: 3

Related Questions