为什么Postgres允许我让列不在Group By中?

时间:2014-04-01 13:56:09

标签: sql postgresql

为什么这个查询:

SELECT inv.batch_number_id AS batch_number_id,
   inv.expiry_date AS expiry_date,
   inv.facility_id AS facility_id,
   inv.id AS id,
   fac.code AS facility_code,
   inv_st.description AS status,
   bn.batch_nbr AS batch_number,
   bn.expiry_date AS batch_expiry_date,
   sum(CASE WHEN al.status_id < 90 THEN al.alloc_qty ELSE 0 END) AS alloc_qty
FROM inventory inv
INNER JOIN facility fac ON inv.facility_id = fac.id
INNER JOIN inventory_status inv_st ON inv.status_id = inv_st.id
LEFT OUTER JOIN batch_number bn ON inv.batch_number_id = bn.id
LEFT OUTER JOIN allocation al ON al.from_inventory_id = inv.id
GROUP BY inv.id,
     facility_code,
     status,
     batch_number,
     batch_expiry_date

在postgres 9.1.6工作?

从文档:&#34;当存在GROUP BY时,SELECT列表表达式无法引用除聚合函数之外的未组合列,因为对于未组合的列表,将返回多个可能的值。柱&#34;

如果我将fac.id添加到select表达式中,我会得到预期的&#34; ERROR:列&#34; fac.id&#34;必须出现在GROUP BY子句中或用于聚合函数&#34;。为什么postgres抱怨该列而忽略了facility_id? (在原始查询中还有很多其他列也以同样的方式违反了我的期望。为了清晰起见,缩短了示例。)

1 个答案:

答案 0 :(得分:5)

The whole quote is

  

当存在GROUP BY时,SELECT列表表达式无法引用未聚合的列,但聚合函数内或未分组的列在功能上依赖于分组列,因为它会否则为一个未分组的列返回多个可能的值。 如果分组列(或其子集)是包含未分组列的表的主键,则存在功能依赖性。

更新:此功能已添加到9.1