Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 count in where condition

Author  Topic 

peace
Constraint Violating Yak Guru

420 Posts

Posted - 2012-06-09 : 12:18:29
how to use COUNT those who wear blue skirts only?

my count has error. how to count only blue skirts?

select column1, column2,
count (select * from tableB where tableB.skirt='blue') as numberOfSkirtsInBlue
from tableA
left join tableB
on tableA.ID=tableB.ID
group by column1, column2

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-09 : 13:29:41
[code]
select column1, column2,
sum (case when tableB.skirt='blue' then 1 else 0 end) as numberOfSkirtsInBlue
from tableA
left join tableB
on tableA.ID=tableB.ID
group by column1, column2
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

peace
Constraint Violating Yak Guru

420 Posts

Posted - 2012-06-10 : 02:05:50
It has ID for each skirts. Can i distinct it to get the accurate amount?

I try this but error on the distinct part.

sum (case when tableB.skirt='blue' and distinct tableB.ID then 1 else 0 end) as numberOfSkirtsInBlue
Go to Top of Page

peace
Constraint Violating Yak Guru

420 Posts

Posted - 2012-06-10 : 02:15:23
i tried this but get this error:

Error converting data type varchar to bigint


sum (case when tableB.skirt='blue' and tableB.ID='select distinct tableB.ID' then 1 else 0 end) as numberOfSkirtsInBlue
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-10 : 02:49:11
[code]
select column1, column2,
count(distinct case when tableB.skirt='blue' then tableB.ID else null end) as numberOfSkirtsInBlue
from tableA
left join tableB
on tableA.ID=tableB.ID
group by column1, column2
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -