我正在尝试group
这样的结果,而不是像这样:
id | nome | bairro
---------------------
1 . |Test 1 | bairro 1
1 . |Test 1 | bairro 2
2 . |Test 2 | bairro 3
它看起来像这样:
id | nome | bairro
----------------------
1 . |Test 1 | bairro 1, bairro 2
2 . |Test 2 | bairro 3
“ id”和“ nome”在表1中,“ bairro”在“ nome”列的table 3
中。
表1
id | nome | situacao
--------------------
1 . |Test 1 | EM_ATIVIDADE
2 . |Test 2 | EM_ATIVIDADE
表2
id | escola (fgk table 1) | bairro (fgk table 3)
-------------------------------------------------
1 . | 2 | 1
2 . | 2 | 2
表3
id | nome
---------------
1 . | bairro 1
2 . | bairro 2
我正在尝试使用LISTAGG
和以下代码进行操作:
SELECT table1.nome, table1.id, LISTAGG(table3.nome, ', ') WITHIN GROUP (ORDER BY table3.nome) as "bairro"
FROM table1
LEFT JOIN table2 on table2.escola = table1.id
LEFT JOIN table3 on table3.id = table2.bairro
WHERE table1.situacao = 'EM_ATIVIDADE'
GROUP BY table1.id, table1.nome
ORDER BY table1.id
执行此操作时,出现错误
ORA-00979:不是按表达式分组
有人可以帮助我吗?我是初学者
edit :已经尝试将table1.nome
添加到我的分组依据。
答案 0 :(得分:2)
我认为这是因为您正在使用一个聚合函数,该函数返回单行,而列将返回多行。因此,您需要对GROUP BY子句中的每个“常规”列进行分组,或者对“常规”列中的值(例如MIN,MAX,SUM等)应用一些汇总函数。
在您的示例中,它将类似于
pip install --upgrade scikit-image
或
SELECT table1.nome, table1.id, LISTAGG(table2.nome, ', ') WITHIN GROUP (ORDER BY table2.nome) as "bairro"
FROM table1
LEFT JOIN table2 on table2.escola = table1.id
LEFT JOIN table3 on table3.id = table2.bairro
WHERE table1.situacao = 'EM_ATIVIDADE'
GROUP BY table1.nome, table1.id
ORDER BY table1.id
还有一种替代方法,就是使用
SELECT MAX(table1.nome), MAX(table1.id), LISTAGG(table2.nome, ', ') WITHIN GROUP (ORDER BY table2.nome) as "bairro"
FROM table1
LEFT JOIN table2 on table2.escola = table1.id
LEFT JOIN table3 on table3.id = table2.bairro
WHERE table1.situacao = 'EM_ATIVIDADE'
ORDER BY table1.id
条款,例如像
OVER (partition BY <column name here>)
有关示例,请参见Oracle docs。
答案 1 :(得分:1)
尝试将您的代码修改为以下内容;
SELECT table1.nome, table1.id, LISTAGG(table1.nome, ', ') WITHIN GROUP (ORDER BY table1.nome, table1.id) as "bairro"
FROM table1
LEFT JOIN table2 on table2.escola = table1.id
LEFT JOIN table3 on table3.id = table2.bairro
WHERE table1.situacao = 'EM_ATIVIDADE'
GROUP BY table1.id, table1.nome
ORDER BY table1.id, table1.nome
我在GROUP BY
中添加了所有非LISTAGG选定的列,也将它们添加到了LISTAGG's ORDER BY
子句中。
除此之外,我还向整个查询的table1.nome
中添加了ORDER BY
,因为我发现执行后显然会更好。
希望我能帮上忙!