从包含sum和count的表中选择多个数据

时间:2014-08-29 05:45:04

标签: mysql sql select left-join where

我的MySQL结构

create table product(id integer(11), name varchar(100));

create table purchase(id_purchase integer(11), user_id integer(11), id_product integer(11), cost integer(11));

insert into product values (1,'product1');
insert into product values (2,'product2');
insert into product values (3,'product3');
insert into product values (4,'product4');

insert into purchase values (1, 1, 4, 10);
insert into purchase values (2, 1, 4, 5);
insert into purchase values (3, 1, 2, 16);

我需要这个结果

id_product | sum(cost) | count
------------------------------
1             0          0
2             16         1
3             0          0
4             15         2

按ID产品分组为一个用户

请帮帮我。

2 个答案:

答案 0 :(得分:0)

在询问这个问题之前,我不确定你做了很多研究......

以下是您要查找的查询:

SELECT PR.id
     ,SUM(P.cost) AS [sum(cost)]
     ,SUM(CASE
             WHEN P.id_product IS NOT NULL THEN 1
             ELSE 0
           END) AS [count]
FROM product PR
LEFT OUTER JOIN purchase P ON P.id_product = PR.id
                            AND P.user_id = ...
GROuP BY PR.id
ORDER BY PR.id

希望这会有所帮助。

答案 1 :(得分:0)

试试这个

select id,case when cost is null then 0 else cost end as sum,
case when p.cnt is null then 0 else p.cnt end as count from
product left join (select id_product,sum(cost) as cost,
count(*) as cnt from purchase group by id_product ) as p on
id=id_product group by id

DEMO