gpt4 book ai didi

mysql - 加入不总结 CASE WHEN

转载 作者:行者123 更新时间:2023-11-30 21:34:09 26 4
gpt4 key购买 nike

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

为清楚起见,我将两个子产品归为同一个名称。

我的问题是,对于我的“收费”金额,它将两个子产品分开,而“预定”金额工作正常。

表格应该是这样的:

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

我很感激我可能没有很好地解释这一点(而且我的代码可能很笨拙 - 我还是个新手!)所以任何帮助/指导都将不胜感激。

谢谢!

最佳答案

一些建议

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

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

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

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

关于mysql - 加入不总结 CASE WHEN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54803827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com