I have a db table like the following with repeated records
Table:
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
I need an output like the following. Is it possible to bring this result with a single SQL?
Output:
product_name type total
-----------------------------------
T-shirt Medium 3
T-Shirt Large 2
Pant Half 3
Shirt Small 1
Actually it will group the same product_name + type and count group items to make the total. The PHP array might be like:
$output = array(
0 => array(
"product_name" => "T-Shirt",
"type" =&开发者_JS百科gt; "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
),
);
A simple aggregate query:
SELECT product_name, type, COUNT(*) AS total
FROM thetable
GROUP BY product_name, type
精彩评论