SQL查询(不带子查询)

时间:2011-05-23 11:04:37

标签: sql postgresql join

我有三张桌子:

user(id, name);

tasks(id, user_id, text, date);

bonus(id, user_id, sum, date, type).

我正在尝试编写一个查询,该列表将为我提供所有用户的列表,他们的任务数量以及每种类型的奖金总额,每个都在单独的列中。

有三种类型的奖金:

type = (1, 2, 3)

所以,我的意思是一张表,看起来像这样

name | task_count | bonus_1 | bonus_2 | bonus_3

3 个答案:

答案 0 :(得分:1)

SELECT u.name, 
        t.task_count, 
        SUM(CASE WHEN b.type=1 then b.sum END) AS bonus_1,
        SUM(CASE WHEN b.type=2 then b.sum END) AS bonus_2,
        SUM(CASE WHEN b.type=3 then b.sum END) AS bonus_3
FROM user u 
LEFT JOIN (SELECT user_id, COUNT(*) AS task_count 
           FROM tasks 
           GROUP BY user_id) t ON t.user_id = u.id
LEFT JOIN bonus b ON b.user_id = u.id 
GROUP BY u.id,u.name,t.task_count

答案 1 :(得分:0)

注意:以下操作无效!保留信息

SELECT
    user.name,
    COUNT(tasks.id) AS task_count,
    SUM(bonus1.sum) AS bonus_1,
    SUM(bonus2.sum) AS bonus_2,
    SUM(bonus3.sum) AS bonus_3
FROM user
    LEFT OUTER JOIN tasks ON tasks.user_id = user.id
    LEFT OUTER JOIN bonus1 ON bonus1.user_id = user.id
        AND bonus1.type = 1
    LEFT OUTER JOIN bonus2 ON bonus2.user_id = user.id
        AND bonus1.type = 2
    LEFT OUTER JOIN bonus3 ON bonus3.user_id = user.id
        AND bonus1.type = 3
GROUP BY
    user.name
ORDER BY
    user.name

如果不是每个用户总是至少有一个任务和至少一种类型的奖励,则可能需要特别处理NULL值。

答案 2 :(得分:0)

在加入user之前,请考虑进行聚合。例如:

select  u.name
,       t.task_count
,       b.bonus_1
,       b.bonus_2
,       b.bonus_3
,       t.comment_count
from    user u
left join
        (
        select  user_id
        ,       count(distinct t.id) as task_count
        ,       count(distinct c.id) as comment_count
        from    tasks t
        left join
                comment c
        on      c.task_id = t.id
        group by
                t.user_id
        ) t
on      t.user_id = u.id
left join
        (
        select  user_id
        ,       sum(case when type = 1 then sum end) as bonus_1
        ,       sum(case when type = 2 then sum end) as bonus_3
        ,       sum(case when type = 3 then sum end) as bonus_2
        from    bonus
        group by
                user_id
        ) b
on      b.user_id = u.id