我想要做的是显示我本月的当前表现,与预期的获胜次数进行比较,然后按产品类型显示总的预期金额。
为清楚起见,我有两个子产品以相同的名称分组。
我的问题是,对于我的“收费”金额,它会将两个子产品分开,因为“计划的”金额可以正常工作。
该表应如下所示:
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
我很欣赏我可能无法很好地解释这一点(而且我的代码可能很笨拙-我还是很新!),所以任何帮助/指导都将不胜感激。
谢谢!
答案 0 :(得分:0)
只是一些建议
您在主选择中有一个列产品,但是您在子查询中输入了而不是产品
您不应在列名周围使用单引号
如果您按用户类型分组,但需要按类型分组以付费
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