Oracle选择并按排除一个字段分组

zkure5ic  于 2022-09-18  发布在  Java
关注(0)|答案(4)|浏览(272)

我有一个非常简单的查询(在Oracle 11g上)来选择3个字段:

select field1, field2, field3, count(*) from table
where...
group by field1, field2, field3
having count(*) > 10;

现在,我需要从“group by”中排除“field3”,因为我只需要对字段1和2进行分组,但我还需要在输出中包含field3。据我所知,SELECT中的所有字段都必须在“GROUP BY”中报告,我该如何处理呢?

谢谢卢卡斯

8gsdolmq

8gsdolmq1#

select t.field1, t.field2, t.field3, tc.Count
from table t
inner join (
    select field1, field2, count(*) as Count
    from table 
    where... 
    group by field1, field2 
    having count(*) > 10 
) tc on t.field1 = tc.field1 and t.field2 = tc.field2
vohkndzv

vohkndzv2#

使用“count”函数的analytical version

select * from (
select field1, field2, field3, count(*) over(partition by field1, field2) mycounter
from table ) 
--simulate the having clause
where mycounter > 10;
fykwrbwg

fykwrbwg3#

如果您不再按field3分组,则每个组可能会突然有不同的field3。您必须决定显示哪一个,例如最大值:

select field1, field2, max(field3), count(*) from table
where...
group by field1, field2
having count(*) > 10;
pb3skfrl

pb3skfrl4#

我知道如何处理的唯一方法是首先隔离Field1和Field2数据并创建一个新表,然后将其链接回添加到Field3中的原始表。

Select Table2.Field1, Table2.Field2, Table1.Field3
From
(Select Field1, max(Field2) as Field2
From Table1) Table2
Where Table2.Field1 = Table1.Field1
And Table2.Field2 = Table1.Field2
Group By
Table2.Field1, Table2.Field2, Table1.Field3

相关问题