2011-09-06 58 views
-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 

我需要像下面的输出。是否有可能将这个结果与一个单一的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 
    ), 
); 

回答

9

一个简单的汇总查询:

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