我有3个人的黄金收入表。当用户获得一些金币时,新记录将通过e_user
和f_value
进入其中一个表格。
现在我要总结每个用户的所有金币,并选择那些收入低于1000的人。
select count(e_user) from (
select count(e_user) from quest_gold union all
select count(e_user) from monster_gold union all
select count(e_user) from other_gold
) AS money
where f_value < 1000
group by e_user
我不确定我的选择是否以正确的方式进行,但它现在给了我“未知的语法错误”。请告诉我这里有什么问题。
答案 0 :(得分:1)
您可以使用having
子句来过滤少于1000的用户,但不能使用count(f_user)
来过滤sum(f_value)
:
select e_user, sum(f_value) as sum_val
from (
select e_user, f_value from quest_gold union all
select e_user, f_value from monster_gold union all
select e_user, f_value from other_gold
) as money
group by e_user
having sum_val < 1000
答案 1 :(得分:0)
赚取少于1000金币的用户应该包括那些一无所获的用户。因此:
select u.user, coalesce(earned.gold, 0) as earned_gold
from users u
left join
(
select e_user, sum(f_value) as gold
from
(
select e_user, f_value from quest_gold
union all
select e_user, f_value from monster_gold
union all
select e_user, f_value from other_gold
) all_gold
group by e_user
) earned on earned.e_user = u.user and earned.gold < 1000
order by u.user;
如果您只想计算少于1000金的用户数:
select count(earned.e_user) as poor_users
from users u
left join
(
select e_user, sum(f_value) as gold
from
(
select e_user, f_value from quest_gold
union all
select e_user, f_value from monster_gold
union all
select e_user, f_value from other_gold
) all_gold
group by e_user
) earned on earned.e_user = u.user and earned.gold < 1000;