繁体   English   中英

加入时不累加情况

[英]Join not summing CASE WHEN

我要做的是显示我本月的当前表现,并与预计的获胜次数进行比较,然后按产品类型显示预期的总金额。

为了清楚起见,我将使用相同的名称分组两个子产品。

我的问题是,对于我的“收费”金额,它会将两个子产品分开,因为“计划的”金额可以正常工作。

该表应如下所示:

Type | Charged | Scheduled | Expected
A      3         2           5
B      1         1           2

实际显示的是:

Type | Charged | Scheduled | Expected
A      2         1           3
A      1         1           2
B      1         1           2

代码如下:

select
t2.product,
t1.Charged,
t2.Scheduled,
t1.charged + t2.scheduled as 'expected'
from(
select
    case
        when user_type = 'a1' then 'a'
        when user_type = 'a2' then 'a'
        else 'b'
    end as 'Type',
    SUM(charged) as 'Scheduled'
from
  table
where
  month(date) = month(now())
and
  year(date) = year(now())
  and status like 'scheduled'
group by 1
order by 2 desc) t2 join 
(select
    case
        when user_type = 'a1' then 'a'
        when user_type = 'a2' then 'a'
        else 'b'
    end as 'Type', 
    sum(charged) as 'Charged'
    FROM table
    WHERE (status = 'Complete'
       AND str_to_date(concat(date_format(date, '%Y-%m'), '-01'), '%Y-%m-%d') = str_to_date(concat(date_format(now(), '%Y-%m'), '-01'), '%Y-%m-%d'))
    GROUP BY user_type
    ORDER BY user_type ASC) as t1 on t1.type = t2.type

我很欣赏我可能无法很好地解释这一点(并且我的代码可能很笨拙-我仍然相当新!),所以任何帮助/指导都将不胜感激。

谢谢!

只是一些建议

您在主选择中有一个列产品,但是您在子查询中输入了而不是产品

您不应该在列名周围使用单引号

您有按user_type分组的广告,但需要按类型分组才能收费

select
t2.type,
t1.Charged,
t2.Scheduled,
t1.charged + t2.scheduled as 'expected'
from(
select
    case
        when user_type = 'a1' then 'a'
        when user_type = 'a2' then 'a'
        else 'b'
    end as Type,
    SUM(charged) as Scheduled
from
  table
where
  month(date) = month(now())
and
  year(date) = year(now())
  and status like 'scheduled'
group by 1
order by 2 desc) t2 join 
(select
    case
        when user_type = 'a1' then 'a'
        when user_type = 'a2' then 'a'
        else 'b'
    end as Type, 
    sum(charged) as Charged
    FROM table
    WHERE (status = 'Complete'
       AND str_to_date(concat(date_format(date, '%Y-%m'), '-01'), '%Y-%m-%d') = str_to_date(concat(date_format(now(), '%Y-%m'), '-01'), '%Y-%m-%d'))
    GROUP BY Type
    ORDER BY Type ASC) as t1 on t1.type = t2.type

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM