2011-09-06 36 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