2

我有两个查询:

1)首先我找到所有独特的name并计算每个独特nameTable

2)第二个我得到每个唯一的行name

代码:

$sql1 = "SELECT name, count(name) as count
    FROM (
        SELECT name
            FROM Table
            WHERE id_city='333' AND id_firm='444' AND id_service='555'
    ) x
    GROUP BY name
";

$res1 = sqlsrv_query($conn, $sql1);

while ($i = sqlsrv_fetch_array($res1, SQLSRV_FETCH_ASSOC))
{
    $name = ($i['name'] != '') ? $i['name'] : '0';

    $sql2 = "SELECT 
        ta.unit as ta_unit,
        ta.id_producer_goods as ta_id_producer_goods
        FROM Table ta
        WHERE ta.id_city='333'
            AND ta.id_firm='444'
            AND ta.id_service='555'
            AND ta.name='$name'";

    $params = array();
    $options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
    $res12 = sqlsrv_query($conn, $sql12, $params, $options);
}

带有结构表的 Sql Fiddle HERE

可以从两个查询中做一个查询吗?

4

2 回答 2

0

假设 unit 和 producer_goods 字段的每个名称有不止一行,并且您希望将它们全部显示。

SELECT ta.[Name],
    (SELECT count([Name]) FROM [Table] tc 
        WHERE tc.[Name] = ta.[Name]
        AND ta.id_city='333' 
        AND ta.id_firm='444' 
        AND ta.id_service='555'
    ) as [Name Count],
    ta.unit as ta_unit,
    ta.id_producer_goods as ta_id_producer_goods
    FROM [Table] ta
    WHERE ta.id_city='333' 
        AND ta.id_firm='444' 
        AND ta.id_service='555' 
    ORDER BY ta.[Name]
于 2013-09-29T04:24:26.423 回答
-1

你需要使用两个查询。由于在第一个查询中调用的组函数将只返回一行。根据您的要求的第 2 点,您需要多行。

于 2013-09-26T09:21:59.370 回答