0

上帝的一天。

我使用 MsSQl Server 2008;

代码:

$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);

}

在这段代码中,我这样做:

1)我选择了所有唯一的namegroup by name);

2) 在第二个 sql($sql11) 中,我确实找到了每个name.

请告诉我,当我可以找到所有唯一的name( group by name) 并计算每个唯一的行时, sql 如何做name

4

2 回答 2

2

您可以在单个语句中获取唯一名称及其计数:

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
于 2013-09-25T14:49:32.750 回答
0
SELECT  colname, count(colname) AS UniqueRecord_Count 
FROM    ascouser
GROUP BY colname

你可以把你想计数的列名放在上面,可以把 Where 子句放在你说的过滤记录上。

于 2013-09-25T15:06:52.673 回答