如何从同一个表中选择不同的Sum值

时间:2015-04-16 07:33:38

标签: php mysql

我有两张桌子:

用户

userid name surname active

活动

userid activity type

有3种类型的活动。

我想根据类型选择所有用户的总活动数。结果集应显示如下:

userid name surname at1 at2 at3

at1代表活动类型1的总活动计数(对于at2和at3相同)。

我尝试使用该查询但返回null。

SELECT u.userid, u.name, u.surname, 
       SUM( a1.activity ) AS at1,
       SUM( a2.activity ) AS at2, 
       SUM( a3.activity ) AS at3
FROM users AS u
INNER JOIN activities AS a1 ON a1.userid = u.userid
INNER JOIN activities AS a2 ON a2.userid = u.userid
INNER JOIN activities AS a3 ON a3.userid = u.userid
WHERE u.active=1
      AND a1.type =1
      AND a2.type =2
      AND a3.type =3

2 个答案:

答案 0 :(得分:2)

你可以这样做(这是伪代码):

select u.name, (SELECT sum(a1.activity) from activities a1 where a1.type=1 and
a1.userid=u.userid) as at1, (SELECT sum(a2.activity) from activities a2 where a2.type=2 and
a2.userid=u.userid) as at2 FROM user AS u group by u.userid

答案 1 :(得分:1)

您可以使用条件和作为

select
u.userid, 
u.name, 
u.surname, 
sum(a.type = 1) as at1,
sum(a.type = 2) as at2,
sum(a.type = 3) as at3
FROM users AS u
INNER JOIN activities AS a ON a.userid = u.userid
group by u.userid