MySQL 使用一个 table 只返回一行
MySQL only returning one row using one table
我想找出总房费和总住宿费(房费和费用),并显示总费用超过 $50 的费用。
我写了这个查询:
SELECT first_name, last_name, expenses, room_rate,
SUM(stays_num*room_rate) as 'total_room_cost',
SUM((stays_num*room_rate)+expenses) as 'total_stay_cost'
FROM assign1.customer
WHERE 'total_stay_cost' < 50
唯一弹出的是 Kristoff Kurn。 Justin Hackman 也应该上来,因为他总共也花了 50 多块。
当你select普通列和聚合函数时,你需要使用GROUP BY
来告诉你希望在哪个上面执行聚合计算。
其次,影响聚合函数结果的条件应该放在 HAVING-clause 中(类似于 where-clause for group by)。
所以你的查询应该是这样的:
SELECT first_name, last_name, expenses, room_rate,
SUM(stays_num*room_rate) as 'total_room_cost',
SUM((stays_num*room_rate)+expenses) as 'total_stay_cost'
FROM assign1.customer
GROUP BY first_name, last_name, expenses, room_rate
HAVING total_stay_cost < 50
您的查询有多个问题:
不要对标识符使用单引号!它们代表文字字符串。
您不能在 where
子句中重用 select
子句中定义的别名(后者在 之前计算 前者)。
聚合部分已关闭:缺少 group by
子句,或者您不应在 select
子句中使用聚合函数
如果您希望每行一个结果满足条件,则:
select c.*,
stays_num * room_rate as total_room_cost,
stays_num * room_rate + expenses as total_stay_cost
from assign1.customer c
where stays_num * room_rate + expenses > 50
如果您希望每个客户一行,那么:
select c.customer_id, c.first_name, c.last_name,
sum(stays_num * room_rate) as total_room_cost,
sum(stays_num * room_rate + expenses) as total_stay_cost
from assign1.customer c
group by c.customer_id
having total_stay_cost > 50
我想找出总房费和总住宿费(房费和费用),并显示总费用超过 $50 的费用。
我写了这个查询:
SELECT first_name, last_name, expenses, room_rate,
SUM(stays_num*room_rate) as 'total_room_cost',
SUM((stays_num*room_rate)+expenses) as 'total_stay_cost'
FROM assign1.customer
WHERE 'total_stay_cost' < 50
唯一弹出的是 Kristoff Kurn。 Justin Hackman 也应该上来,因为他总共也花了 50 多块。
当你select普通列和聚合函数时,你需要使用GROUP BY
来告诉你希望在哪个上面执行聚合计算。
其次,影响聚合函数结果的条件应该放在 HAVING-clause 中(类似于 where-clause for group by)。
所以你的查询应该是这样的:
SELECT first_name, last_name, expenses, room_rate,
SUM(stays_num*room_rate) as 'total_room_cost',
SUM((stays_num*room_rate)+expenses) as 'total_stay_cost'
FROM assign1.customer
GROUP BY first_name, last_name, expenses, room_rate
HAVING total_stay_cost < 50
您的查询有多个问题:
不要对标识符使用单引号!它们代表文字字符串。
您不能在
where
子句中重用select
子句中定义的别名(后者在 之前计算 前者)。聚合部分已关闭:缺少
group by
子句,或者您不应在select
子句中使用聚合函数
如果您希望每行一个结果满足条件,则:
select c.*,
stays_num * room_rate as total_room_cost,
stays_num * room_rate + expenses as total_stay_cost
from assign1.customer c
where stays_num * room_rate + expenses > 50
如果您希望每个客户一行,那么:
select c.customer_id, c.first_name, c.last_name,
sum(stays_num * room_rate) as total_room_cost,
sum(stays_num * room_rate + expenses) as total_stay_cost
from assign1.customer c
group by c.customer_id
having total_stay_cost > 50