【问题标题】:what effect does parenthesis have when selecting a column in SQL?SQL中选择列时括号有什么作用?
【发布时间】:2020-03-06 20:21:16
【问题描述】:

我在 Redshift (postgreSQL) 中有一个不寻常的问题。在这里复制太长了,但我团队中有人有这样的代码:

select (year) as year, (month) as month, (other_col) as other_col, sum(numerical_val) as num
from big_table
where (a few conditions)
group by (year), (month), (other_col)
union
select (year) as year, (month) as month, (other_col) as other_col, sum(numerical_val) as num
from big_table
where (more specific condition)
group by (year), (month), (other_col);

我认为没有必要将(年份)作为年份等,所以我删除了它们并这样做:

select year, month, other_col, sum(numerical_val) as num
from big_table
where (a few conditions)
group by year, month, other_col
union
select year, month, other_col, sum(numerical_val) as num
from big_table
where (more specific condition)
group by year, month, other_col;

我希望得到相同的输出,但 numeric_val 的差异只有百分之几。那是什么呀?

我尝试了几次实验,并且仅使用一个查询(无联合),与“(年)作为年”等相比,使用“年”得到了相同的确切结果。联合发生了一些变化。

你能猜出为什么“(年)作为年”部分会改变联合中的输出吗?

【问题讨论】:

  • 可能是查询结果缓存?您更改了查询文本,使其在逻辑上保持不变,但原始查询可能已被缓存
  • 您能否提供一些示例输入和输出来演示您所描述的内容?

标签: sql postgresql select amazon-redshift


【解决方案1】:

sum()ed 号码的数据类型是什么?

特别是浮点类型是近似的。此外,将它们相加的顺序会影响结果。这与根据加法顺序以不同方式累积的舍入误差有关。

你没有提供太多信息,所以这是我最好的猜测,为什么你会得到相似但略有不同的答案。

【讨论】:

    猜你喜欢
    • 2015-11-30
    • 1970-01-01
    • 2012-05-01
    • 2018-10-13
    • 2022-01-06
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2012-02-12
    相关资源
    最近更新 更多