我有两个问题:
1)首先,我找到所有唯一name
并计算name
Table
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使用结构表HERE
可以从两个查询中执行一个查询吗?
答案 0 :(得分: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]
答案 1 :(得分:-1)
您需要使用两个查询。由于在第一个查询中调用的组函数将只返回一行。 虽然根据您的要求的第2点需要多行。