【问题标题】:'Group by' calculations don't match expected results“分组依据”计算与预期结果不符
【发布时间】:2018-03-18 22:06:57
【问题描述】:

这是我的查询:

select product_name, (sum(item_price - discount_amount) * (quantity)) AS product_total
from products inner join order_items 
using(product_id) 
group by product_name

我的查询输出:

预期输出:

我几乎可以显示所有内容,但 Gibson Les Paul product_total 是错误的,最后一行没有显示 Null 及其 product_total

【问题讨论】:

  • 更新您的问题并显示您的相关表架构..
  • (“NULL”很有趣,无论如何 - 产品有 id,但没有名字?外部加入?)
  • @greybeard 一开始我也这么认为,但这是一个汇总值。

标签: mysql sql


【解决方案1】:

内连接意味着您只会看到具有 product_name 的 order_items。使用外连接查看没有 product_name 的 order_items。此外,您的 sum 应该是最外层的函数。可能是这样的:

select product_name, sum((item_price - discount_amount) * (quantity)) AS product_total
from order_items left join products 
  on order_items.product_id=products.product_id
group by product_name 

如果需要,请查找内部和外部联接的说明,例如 like this question

但是,仔细观察您的数据,连接类型可能不是null 行的问题。底行只是所有其他行的总和,因此在 group by 子句后添加 with rollup 将得到该行。

【讨论】:

  • 产生与我的查询相同的输出
  • 也许给我们一个来自两个表的数据样本,包括产品名称为空的行。
  • 我已经通过汇总更新了我的答案并更改了函数的位置。
  • 我相信“Null”是 Product_total 的总和,不确定如何合并
  • 使用with rollup
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 2023-03-13
  • 2014-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多