Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Row count based on column value - How can I do this? 1

Status
Not open for further replies.

southbeach

Programmer
Jan 22, 2008
879
US
Given tableA and colSize, I need a row count for each value in colSize.

Values can be 10, 20 and 40

tableA has a unique key that I intend to use to match my query against.

So, if I had rows

key colSize
----+--------
1 10
2 40
3 20
4 20
5 40

I expect counts to be

Count Size
-----+------
1 10
2 20
2 40

I know of COUNT(*) but I cannot figure out how to do multiple count and conditions within a single query.

Thank you all for your help!


 
OK - I think I came up with a solution

Code:
 SELECT * ,
CASE WHEN size = 40 THEN COUNT( * ) END AS count40,
CASE WHEN size = 20 THEN COUNT( * ) END AS count20,
CASE WHEN size = 10 THEN COUNT( * ) END AS count10
FROM tableA WHERE key = value GROUP BY size

Not sure how expensive this is, but for now, it is all I got.
 
Give this a try:
Code:
SELECT count(*)
       , colSize
FROM tableA
GROUP BY colSize
 
This works if I only wanted a quick query without assigning the respective counts to a specific variable.

You see, I am using this query within a PHP application and need to reference the count values.

Thanks!
 
I'd suggest using the query I provided and ask in the PHP forum how to better assign the variable based on the query results. It seems you should be able to do some checks in PHP (I'm not a PHP guy) to determine what colSize is and assign the count(*) to a variable.
 
Code:
$query = "
SELECT colSize, count(*)
FROM tableA
GROUP BY colSize";

$result = mysql_query($query) or die( mysql_error());

$data = array();
while ($rows = mysql_fetch_row($result)){
$size = $rows[0];
$count = $rows[1];

$data[$size] = $count;
}

To retrieve the values...
Code:
echo $data[40] . "\n";
echo $data[10] . "\n";

Or use foreach...
Code:
foreach ($data as $k=>$v){
echo "Size=$k and Count=$v \n";
}
Returns...
Code:
2
1

Mark
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top