TysonLPrice
Programmer
I always have trouble with this kind of query. I'm trying to count the number of occurences of a column with a given value in a range. The data is:
create table ##Steve(Year varchar(4),flag char(1))
insert into ##Steve(year,flag) values('2000','A')
insert into ##Steve(year,flag) values('2000','C')
insert into ##Steve(year,flag) values('2000','B')
insert into ##Steve(year,flag) values('2001','A')
insert into ##Steve(year,flag) values('2001','B')
insert into ##Steve(year,flag) values('2001','B')
insert into ##Steve(year,flag) values('2001','C')
insert into ##Steve(year,flag) values('2002','A')
insert into ##Steve(year,flag) values('2002','A')
insert into ##Steve(year,flag) values('2002','B')
insert into ##Steve(year,flag) values('2002','C')
the expected output is:
Year A B C
2001 1 2 1
2002 2 1 1
I've been trying pivot, cube and rollup but I'm getting no where. This was my last attempt to show what I am trying:
select year,
count(case when flag = 'A' then flag end) as a,
count(case when flag = 'B' then flag end) as b,
count(case when flag = 'C' then flag end) as c
from ##Steve
where year between '2001' and '2002'
group by year,flag with rollup
It is not what I'm looking for.
create table ##Steve(Year varchar(4),flag char(1))
insert into ##Steve(year,flag) values('2000','A')
insert into ##Steve(year,flag) values('2000','C')
insert into ##Steve(year,flag) values('2000','B')
insert into ##Steve(year,flag) values('2001','A')
insert into ##Steve(year,flag) values('2001','B')
insert into ##Steve(year,flag) values('2001','B')
insert into ##Steve(year,flag) values('2001','C')
insert into ##Steve(year,flag) values('2002','A')
insert into ##Steve(year,flag) values('2002','A')
insert into ##Steve(year,flag) values('2002','B')
insert into ##Steve(year,flag) values('2002','C')
the expected output is:
Year A B C
2001 1 2 1
2002 2 1 1
I've been trying pivot, cube and rollup but I'm getting no where. This was my last attempt to show what I am trying:
select year,
count(case when flag = 'A' then flag end) as a,
count(case when flag = 'B' then flag end) as b,
count(case when flag = 'C' then flag end) as c
from ##Steve
where year between '2001' and '2002'
group by year,flag with rollup
It is not what I'm looking for.