我有一个查询,返回的数据如下:
REF01 10 50 1
REF01 10 50 1
REF01 20 40 1
REF01 20 40 1
REF01 30 30 2
REF02 40 20 1
REF02 50 10 2
REF02 50 10 2
我需要它像这样返回它:
REF01 60 120
REF02 90 30
为此,我首先添加一个DISTINCT
(GROUP BY
的所有列也都执行相同的操作),以删除重复项,并返回如下内容:
REF01 10 50 1
REF01 20 40 1
REF01 30 30 2
REF02 40 20 1
REF02 50 10 2
然后我需要添加一个SUM()
的结果,而不会计算删除的重复项。
我尝试了类似this one之类的解决方案,但是我遇到FROM (SELECT ...)
和this one的错误,除了子查询中的一列是操作的结果( column_1-column_2-column_3
),该错误导致错误ORA-00972: identifier is too long
超过了30个字符的最大限制,并尝试在子查询中应用带有AS
的别名(在WITH SUBQUERY AS ( ... )
中不起作用我尝试过的MS查询。
对大多数SQL函数的支持并不是Microsoft Query上最好的。
答案 0 :(得分:1)
编辑-这是有效的解决方案:
该问题似乎与自动生成的列名有关,最终对于oracle来说太长了。为避免此问题,查询可以显式命名CTE列,如下所示:
with
x (col1, col2, col3, col4) as ( -- columns are named here
select distinct col1, col2, col3, col4 from t
)
select col1, sum(col2), sum(col3)
from x
group by col1
解决方案2(在该工具中不起作用):
如果您使用的工具不支持子查询,您仍然可以通过创建视图来欺骗它。例如:
create view view1 as select distinct col1, col2, col3, col4 from t
然后,运行一个使用它的查询:
select col1, sum(col2), sum(col3) from view1 group by col1
结果:
COL1 SUM(COL2) SUM(COL3)
----- --------- ---------
REF02 90 30
REF01 60 120
解决方案3(在该工具中也不起作用):
select col1, sum(col2), sum(col3) from (
select distinct col1, col2, col3, col4 from t
) x
group by col1
用于测试的数据
作为参考,我使用的数据脚本是:
create table t (
col1 varchar2(10),
col2 number(6),
col3 number(6),
col4 number(6)
);
insert into t (col1, col2, col3, col4) values ('REF01', 10, 50, 1);
insert into t (col1, col2, col3, col4) values ('REF01', 10, 50, 1);
insert into t (col1, col2, col3, col4) values ('REF01', 20, 40, 1);
insert into t (col1, col2, col3, col4) values ('REF01', 20, 40, 1);
insert into t (col1, col2, col3, col4) values ('REF01', 30, 30, 1);
insert into t (col1, col2, col3, col4) values ('REF02', 40, 20, 1);
insert into t (col1, col2, col3, col4) values ('REF02', 50, 10, 1);
insert into t (col1, col2, col3, col4) values ('REF02', 50, 10, 1);
答案 1 :(得分:1)
似乎很明显,但这行不通(修订)吗?
select col1, sum(col2) as col2, sum(col3) as col3 from
(Select col1, col2, sum(DISTINCT col3) as col3 from t
group by col1, col2) aa
group by col1
或带有WITH:
WITH tt as (Select col1, col2, sum(DISTINCT col3) as col3 from t
group by col1, col2)
select col1, sum(col2) as col2, sum(col3) as col3 from tt
group by col1