Q:

How get rows and get count rows for each unique param in one sql?

God day.
I use MsSQl Server 2008;
Code:
$entersql="SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='$id_city' AND id_firm='$id_firm' AND id_service='$id_service'
) x
GROUP BY name
";

$enterres = sqlsrv_query($conn, $entersql, $params, $options);

while($i = sqlsrv_fetch_array($enterres, SQLSRV_FETCH_ASSOC))
{

if($inputby=='id_hist_answer'&&$typeby=='DESC'){$a--;}else{$a++;}

$name=($i['name']!='')? $i['name']:'0';

$sql11="SELECT 
ha.unit as ha_unit,
ha.id_producer_goods as ha_id_producer_goods
FROM Hist_answer ha
WHERE ha.id_city='$id_city' AND ha.id_firm='$id_firm' AND ha.id_service='$id_service' AND ha.name='$name'";

$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$res11 = sqlsrv_query($conn, $sql11,$params,$options);

$row_count_ha = sqlsrv_num_rows($res11);

}

In this code i do:
1) i selected all unique name (group by name);
2) in second sql($sql11) i do find count rows for each name.
Tell me please how do sql when i can find all unique name (group by name) and count rows for each unique name ?

A:

You can get unique names and their counts in a single statement:
SELECT  name, count(name) AS records 
FROM    Hist_answer
WHERE   id_city='$id_city' 
    AND id_firm='$id_firm' 
    AND id_service='$id_service'
GROUP BY name

