我有以下SQL:
select
inv.salesman_id,
(select salesman_goals.goal from salesman_goals
where salesman_goals.salesman_id = inv.salesman_id
and salesman_goals.group_id = g.group_id
and salesman_goals.subgroup_id = sg.subgroup_id
and salesman_goals.variation_id = v.variation_id)
as goal,
sum(i.quantity) as qnt
from invoiceitem i
inner join invoice inv on inv.invoice_id = i.invoice_id
inner join product p on p.product_id = i.product_id
left join groups g on g.group_id = p.group_id
left join subgroup sg on sg.group_id = g.group_id and sg.subgroup_id = p.subgroup_id
left join variation v on v.group_id = sg.group_id and v.subgroup_id = sg.subgroup_id and v.variation_id = p.variation_id
group by
1,2
返回三列,第一列是销售员ID,第二列是获取销售数量目标的子选择,第三列是实际销售数量。 即使按第一列和第二列分组,firebird在执行查询时也会抛出错误:
Invalid expression in the select list (not contained in either an aggregate function or the GROUP BY clause).
这是什么原因?
答案 0 :(得分:4)
选择列表中有一列"(未包含在聚合函数或GROUP BY子句中)"。即您在子选择中提到的每个列,而不是inv.salesman_id
。这样的列每组有许多值。当存在GROUP BY(或只是HAVING,由所有列隐式分组)时,SELECT子句每组返回一行。没有单一的价值可以返回。所以你想(当你自己回答)时:
group by
inv.salesman_id,
g.group_id,
sg.subgroup_id,
v.variation_id
答案 1 :(得分:2)
好的家伙我找到了解决这个问题的方法。
问题是,如果列中的子查询位于group by
子句中,则此子查询中的参数也必须出现在group by
中。所以在这种情况下,我所要做的就是:
group by
inv.salesman_id,
g.group_id,
sg.subgroup_id,
v.variation_id
就是这样。希望将来有人遇到同样的问题会有所帮助。