需要sql查询帮助来查找配置文件贡献吗?

时间:2018-08-09 12:29:56

标签: sql oracle mysqli

我有两个表,一个用于用户配置文件(mls_user),第二个用于用户活动(mls_entry)。

下表(mls_user)用于配置文件用户,我在其中存储用户的所有信息。

=====================================================
|| user_id || user_name || user_role || user_email ||
=====================================================
||   140   ||  santosh  ||     2     ||san@mail.com||
||   150   ||  Deepak   ||     2     ||dep@mail.com||
||   152   ||  sandeep  ||     2     ||sad@mail.com||
=====================================================

我有第二个表(mls_entry),用于存储用户活动,如下所示:

=======================================================
|| id || user_id || category || Distance ||  status  ||
|| 1  ||   140   || running  ||    10    || approved ||
|| 2  ||   140   || running  ||    20    || approved ||
|| 3  ||   140   || cycling  ||    40    || rejected ||
|| 4  ||   140   || cycling  ||    20    || approved ||
|| 5  ||   150   || running  ||    15    || approved ||
|| 6  ||   152   || cycling  ||    50    || approved ||
=======================================================

现在我想要:

==================================================================
|| user_name || runing_entry || cycling_entry || total_distance ||
==================================================================
|| santosh   ||     2        ||     2         ||      50        ||
|| deepak    ||     1        ||     1         ||      15        ||
|| sandeep   ||     1        ||     1         ||      50        ||
==================================================================

因此,我无法为此找到解决方案。我已经尝试了以下查询,但结果显示错误。

SELECT mls_user.name,
(CASE 
   WHEN mls_entry.category='running' 
   THEN SUM(mls_entry.category='running') 
   ELSE 0 END) AS runnerEntry,
(CASE 
   WHEN mls_entry.category='cycling' 
   THEN SUM(mls_entry.category='cycling') 
   ELSE 0 END) AS cyclingEntry,
(CASE
WHEN SUM(mls_entry.distance) AND mls_entry.category='running' AND mls_entry.status='approved' 
THEN SUM(mls_entry.distance) ELSE 0 END) AS total_point_runner FROM mls_user LEFT JOIN mls_entry ON mls_user.id = mls_entry.user_id GROUP BY mls_user.id HAVING mls_user.role = 2

2 个答案:

答案 0 :(得分:1)

我会进行条件聚合:

select u.user_name, u.user_id
       sum(case when category = 'running' then 1 else 0 end) as running,
       sum(case when category = 'cycling' then 1 else 0 end) as running,
       sum(case when status = 'approved' then distance else 0 end) as distance
from mls_user u join
     mls_entry e
     on e.user_id = u.user_id
group by u.user_name, u.user_id;

答案 1 :(得分:0)

尝试一下

Select user_name,user_id
,(Select Count(ID) From mls_entry Where mls_entry.user_id=mls_user.user_id AND category='running' As X) As runing_entry
,(Select Count(ID) From mls_entry Where mls_entry.user_id=mls_user.user_id AND category='cycling' As Y) As cycling_entry
,(Select SUM(total_distance) From mls_entry Where mls_entry.user_id=mls_user.user_id As Z) As total_distance
From mls_user