我有一个db表,如下所示,带有重复记录
表格
product_name type
--------------------------------
T-Shirt Medium
T-Shirt Large
Pant Half
Shirt Small
T-Shirt Medium
Pant Half
Pant Half
T-Shirt Large
T-Shirt Medium
我需要一个如下输出。是否可以将此结果与单个SQL结合使用?
输出:
product_name type total
-----------------------------------
T-shirt Medium 3
T-Shirt Large 2
Pant Half 3
Shirt Small 1
实际上,它会将相同的product_name +类型和计数组项目分组以进行总计。 PHP数组可能类似于:
$output = array(
0 => array(
"product_name" => "T-Shirt",
"type" => "Medium",
"total" => 3
),
1 => array(
"product_name" => "T-Shirt",
"type" => "Large",
"total" => 2
)
2 => array(
"product_name" => "Pant",
"type" => "Half",
"total" => 3
),
3 => array(
"product_name" => "Shirt",
"type" => "Small",
"total" => 1
),
);
答案 0 :(得分:9)
一个简单的聚合查询:
SELECT product_name, type, COUNT(*) AS total
FROM thetable
GROUP BY product_name, type