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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 select a variable column name

Author  Topic 

dulaney84
Starting Member

3 Posts

Posted - 2008-12-22 : 16:21:25
I am working on showing a menu on a web page and want to display the count of each item for gender. I'll try to explain what I am looking for. The product table has a column for each gender type (Mens, Ladies, Child) which is a bit field of true or false depending on if it is for that type (it can be multiple types)
I have another table that just lists the genders.

Here is what I am trying to write:
SELECT Gender as @ColName,
(SELECT COUNT(*) AS Expr1
FROM Products AS H
WHERE (@ColName = 1)) AS RecordCount
FROM Gender AS C

So when it is finished, I want it to display for example:
Mens (12)
Ladies (20)
Child (3)
that I can bind to my gridview is my asp.net project.

Is there a way to do this? When the select statement runs, I want to select the Gender (which on the first pass will be Mens) and then count the number of times the column Mens has a true value.
I don't know how to use the variable @ColName in the WHERE clause or if it is even possible to do this.
Thanks.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-12-22 : 16:53:23
SELECT Gender, COUNT(*)
FROM Products
GROUP BY Gender

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2008-12-22 : 17:03:56
Looks like you have your data "normalized" so a simple GROUP BY may not work.

you cant use variables that way but here is one way. (you can also look at UNPIVOT in Books Online)

--------------------------
--set up sample data
declare @products table (prodID int, Mens bit, Ladies bit, child bit)
declare @gender table (gender varchar(12))

insert @gender
select 'Mens' union all
select 'Ladies' union all
select 'Child'

insert @products
select 1, 1, null, null union all
select 2, 1, null, 1 union all
select 3, 1, 1, 1
--------------------------

select g.gender + ' (' + convert(varchar,
count(case
when g.gender = 'Mens' then p.Mens
when g.gender = 'Ladies' then p.Ladies
when g.gender = 'Child' then p.Child
end
)) + ')'
from @products p
cross join @gender g
group by g.gender
order by 1 desc

OUTPUT:
Mens (3)
Ladies (1)
Child (2)


EDIT:
I meant "de-normalized"


Be One with the Optimizer
TG
Go to Top of Page
   

- Advertisement -