【问题标题】:MySQL only returning one row using one tableMySQL 只使用一张表返回一行
【发布时间】:2020-10-01 21:20:17
【问题描述】:

我想查找总房间费用和总住宿费用(房间和费用),并显示总费用超过 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。贾斯汀哈克曼也应该上来,因为他总共也花了 50 多。

【问题讨论】:

  • 你想GROUP BY
  • 'total_stay_cost' &lt; 50 没有意义,您正在将字符串与数字进行比较(并且运算符与您的要求相矛盾,您想要total_stay_cost &gt; 50

标签: mysql sql sum where-clause having-clause


【解决方案1】:

当您选择普通列和聚合函数时,您需要使用GROUP BY 来告诉您要执行哪些聚合计算。

其次,影响聚合函数结果的条件应该放在 HAVING 子句中(类似于 group by 的 where 子句)。

所以你的查询应该是这样的:

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

【讨论】:

    【解决方案2】:

    您的查询有多个问题:

    • 不要使用单引号作为标识符!它们代表文字字符串。

    • 您不能在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
    

    【讨论】:

      猜你喜欢
      • 2015-01-22
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多