提问人:Shashikanth D 提问时间:11/10/2023 最后编辑:Thorsten KettnerShashikanth D 更新时间:11/11/2023 访问量:68
选择查询:消除重复的重复行,而不进行分组依据
Select Query: Elimate repeated duplicate rows without group by
问:
我有一张这样的表,其中 Student(id, attempt) 数据如下:
编号 | 尝试 |
---|---|
1 | 1 |
1 | 2 |
1 | 3 |
1 | 4 |
2 | 1 |
2 | 2 |
我想找到学生的最高尝试次数 EX:Student1 在第 3 次尝试中通过了考试
最终输出必须像
编号 | 尝试 |
---|---|
1 | 4 |
2 | 2 |
我不想使用 where 分组依据,因为我正在创建一个视图并将联接多个表
INNER JOIN (SELECT id, MAX(attempts)as MaxCreated
FROM SHRTCKG
GROUP BY id, attempts) u
ON x.id = u.attempts
AND x.id = u.attempts)
答:
0赞
SelVazi
11/10/2023
#1
如果无法使用,我们可以使用窗口函数:MAX()
GROUP BY
select distinct id, MAX(attempt) over (partition by id) as attempt
from mytable
评论
0赞
Shashikanth D
11/10/2023
它不会重复我试图在这里创建一个视图的行吗
0赞
SelVazi
11/10/2023
使用“distinct”将防止重复检查我的更新
1赞
Thorsten Kettner
11/10/2023
#2
您是否正在寻找每个 ID 的最大尝试次数并显示按 ID 排序的结果?这是最基本的聚合:
select id, max(attempt)
from shrtckg
group by id
order by id;
0赞
Saikat
11/10/2023
#3
下面是使用 SQL Server 的查询。这基本上是每个 ID 的最大尝试值。
select
id ,
max(attempt) as max_attempt from Student as a
group by id;
0赞
d r
11/10/2023
#4
如果你希望它没有 WHERE 和 GROUP BY(虽然不知道为什么),那么解决方案可能是 MODEL 子句(带有 Distinct):
WITH -- S a m p l e D a t a :
tbl (ID, ATTEMPT) As
( Select 1, 1 From Dual Union All
Select 1, 2 From Dual Union All
Select 1, 3 From Dual Union All
Select 1, 4 From Dual Union All
Select 2, 1 From Dual Union All
Select 2, 2 From Dual
)
...代码如下:
-- M a i n S Q L :
SELECT Distinct ID, COUNT_ATTEMPT "ATTEMPT"
FROM ( Select ID, ATTEMPT, 0 "COUNT_ATTEMPT" From tbl )
MODEL Dimension By ( ID, ATTEMPT )
Measures ( COUNT_ATTEMPT )
RULES ( COUNT_ATTEMPT[ANY, ANY] = Count(COUNT_ATTEMPT)[CV(ID), ATTEMPT > 0] )
... ...
-- R e s u l t :
-- ID ATTEMPT
-- ---------- ----------
-- 1 4
-- 2 2
0赞
SSS
11/10/2023
#5
您可以使用如下所示的标量子查询:
select distinct id,
(select MAX(attempt)
from mytable t2
where t2.id = t.id) as attempt
from mytable t
评论