你能帮我解决一下这个sql问题吗?

时间:2011-09-06 11:37:48

标签: php sql

我有一个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
    ),
);

1 个答案:

答案 0 :(得分:9)

一个简单的聚合查询:

SELECT product_name, type, COUNT(*) AS total
FROM thetable
GROUP BY product_name, type