开发者

Can you please help me to build this sql problem?

开发者 https://www.devze.com 2023-04-03 12:11 出处:网络
I have a db table like the following with repeated records Table: product_nametype --------------------------------

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
0

精彩评论

暂无评论...
验证码 换一张
取 消