2014-04-01 76 views
0

爲什麼這個查詢:爲什麼Postgres允許我的列不在組中?

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工作?

來自文檔:「當存在GROUP BY時,除了集合函數內,SELECT列表表達式無法引用未分組的列,因爲對於未分組的列將有多個可能的值返回。 「

如果我將fac.id添加到select表達式中,我得到預期的「ERROR:column」fac.id「必須出現在GROUP BY子句中或用於聚合函數中」。爲什麼postgres抱怨這個專欄但忽略了facility_id? (這裏是一大堆在原來的查詢也違揹我以同樣的方式期望其他列的例子是縮短了清晰度。)

+0

顯示錶結構'\ d inventory'' \ d facility'''d inventory_status'。這裏的關鍵術語是'函數依賴關係' –

+0

從手冊:「*當存在GROUP BY時,SELECT列表表達式無法引用除聚合函數**之外的未分組列,或者未分組列在功能上依賴在分組列上** [...]如果分組列(或其子集)是包含未分組列的表的主鍵,則存在函數依賴項。*「 –

回答

5

The whole quote is

When GROUP BY is present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions or if the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column.

UPDATE:此功能添加到9.1

+0

我的報價是針對版本8的文檔。 (第一個谷歌返回(愚蠢,是))。我檢查了各種版本的更新日誌,但一定是錯過了。謝謝! – marky1991

相關問題