Php 你能帮我解决这个sql问题吗?
我有一个db表,如下所示,有重复记录 表格:Php 你能帮我解决这个sql问题吗?,php,sql,Php,Sql,我有一个db表,如下所示,有重复记录 表格: product_name type -------------------------------- T-Shirt Medium T-Shirt Large Pant Half Shirt Small T-Shirt Medium Pant
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
product_name type total
-----------------------------------
T-shirt Medium 3
T-Shirt Large 2
Pant Half 3
Shirt Small 1
我需要如下输出。是否可以用一个SQL带来这个结果
输出:
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
product_name type total
-----------------------------------
T-shirt Medium 3
T-Shirt Large 2
Pant Half 3
Shirt Small 1
实际上,它将对相同的产品名称+类型进行分组,并对分组项目进行计数,从而得出总数。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
),
);
一个简单的聚合查询:
SELECT product_name, type, COUNT(*) AS total
FROM thetable
GROUP BY product_name, type