列 'Comptes.CO_NUMERO' 在 select 列表中无效,因为它未包含在聚合函数或 GROUP BY 子句中

Column 'Comptes.CO_NUMERO' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

我正在尝试按 "column 1" 和 "column 5" 进行分组,并对第 2、3、4 列求和

但它不起作用。请帮忙

这是我的查询

SELECT Post,Montant_Brut,Montant_AP,Net_1,Rubrique,OP_EXERCICE_COMPTA from(
select 
(case when left(C.CO_NUMERO,3) like '_9_' or left(C.CO_NUMERO,3) like '_8_' then (SUBSTRING(C.CO_NUMERO, 1, 1) + SUBSTRING(C.CO_NUMERO, 3, 1) + SUBSTRING(C.CO_NUMERO, 4, 1)) else left(C.CO_NUMERO,3) end ) as Post,
(case when left(C.CO_NUMERO,3) like '_9_' or left(C.CO_NUMERO,3) like '_8_' then sum (0) else (sum(C.CO_MONTANT)) end) as Montant_Brut,
(case when left(C.CO_NUMERO,3) like '_9_' or left(C.CO_NUMERO,3) like '_8_' then (sum(C.CO_MONTANT)) else sum(0) end) as  Montant_AP,
(case when O.OP_TYPE like 'Anouveaux' then (sum(C.CO_MONTANT)) else sum(0) end) Net_1,
(case when left(C.CO_NUMERO,2) like '_9' or left(C.CO_NUMERO,2) like '_8' then (SUBSTRING(C.CO_NUMERO, 1, 1) + SUBSTRING(C.CO_NUMERO, 3, 1)) when left(C.CO_NUMERO,2) like '25' then '24' else left (C.CO_NUMERO,2) end ) as Rubrique,
O.OP_EXERCICE_COMPTA 
from Operations O inner join Comptes  C on O.OP_ID = C.CO_OP_NUMERO WHERE ((C.CO_NUMERO between '21%' and '40%') or (C.CO_NUMERO  like '51%') ) and O.OP_EXERCICE_COMPTA = 11
) a group by Post, Rubrique

让我们尽力帮助您。

首先,您需要了解 group by 子句。正是分组依据使您能够计算或对结果求和,并且仍然能够保留密钥。

因此,当您尝试对 c.co_montant 求和时,您将失去使用 c.co_numero 的权利。

除了这一点,你的查询对我来说几乎不错。

试试这个版本:

SELECT Post
,sum(Montant_Brut)
,sum(Montant_AP)
,sum(Net_1)
,Rubrique
,sum(OP_EXERCICE_COMPTA)
from(
    select 
    (case when left(C.CO_NUMERO,3) like '_9_' or left(C.CO_NUMERO,3) like '_8_' then (SUBSTRING(C.CO_NUMERO, 1, 1) + SUBSTRING(C.CO_NUMERO, 3, 1) + SUBSTRING(C.CO_NUMERO, 4, 1)) else left(C.CO_NUMERO,3) end ) as Post,
    (case when left(C.CO_NUMERO,3) like '_9_' or left(C.CO_NUMERO,3) like '_8_' then 0 else (C.CO_MONTANT) end) as Montant_Brut,
    (case when left(C.CO_NUMERO,3) like '_9_' or left(C.CO_NUMERO,3) like '_8_' then (C.CO_MONTANT) else 0 end) as  Montant_AP,
    (case when O.OP_TYPE like 'Anouveaux' then (C.CO_MONTANT) else 0 end) Net_1,
    (case when left(C.CO_NUMERO,2) like '_9' or left(C.CO_NUMERO,2) like '_8' then (SUBSTRING(C.CO_NUMERO, 1, 1) + SUBSTRING(C.CO_NUMERO, 3, 1)) when left(C.CO_NUMERO,2) like '25' then '24' else left (C.CO_NUMERO,2) end ) as Rubrique,
    O.OP_EXERCICE_COMPTA 
from Operations O inner join Comptes  C on O.OP_ID = C.CO_OP_NUMERO WHERE ((C.CO_NUMERO between '21%' and '40%') or (C.CO_NUMERO  like '51%') ) and O.OP_EXERCICE_COMPTA = 11
) a group by Post, Rubrique

我采用了你的求和操作,然后将结果放入 group by 子句中。

只要我无法测试该代码,我希望你能告诉我它是否有效。