gpt4 book ai didi

sql - 如何在oracle中选择不同的记录?

转载 作者:行者123 更新时间:2023-12-02 19:41:35 26 4
gpt4 key购买 nike

我想在某些条件下选择不同的行,但是当我在 select 语句中添加 id 列时,它会返回所有行???

下面的查询工作正常

select distinct dst_bnk_acnt_id
,dst_cust_id
,org_cust_id
,dst_pos_id
,pmt_typ_cd
from tb_cm_t_pmt_coll
where org_pos_id = 8 OR dst_pos_id = 8 OR dst_bnk_acnt_id = 1 ;

但是当我想使用 order by id(desc) 选择最新记录时,它会返回所有行!

SELECT  distinct id
,dst_bnk_acnt_id
,dst_cust_id
,org_cust_id
,dst_pos_id
,pmt_typ_cd
FROM tb_cm_t_pmt_coll
WHERE org_pos_id = 8 OR dst_pos_id = 8 OR dst_bnk_acnt_id = 1
ORDER BY id DESC;

我知道“id”列是主键,它的所有值都是唯一的,因此所有行都变得唯一。

我想仅使用这些[dst_bnk_acnt_id,dst_cust_id,org_cust_id,dst_pos_id,pmt_typ_cd]列来选择不同的行,但我也想使用 id 按降序对它们进行排序订单。

请帮忙。

最佳答案

我没有您的表格,因此我将使用 Scott 的示例架构。

不同的部门和职位是:

SQL> select distinct deptno, job from emp;

DEPTNO JOB
---------- ---------
20 CLERK
30 SALESMAN
20 MANAGER
30 CLERK
10 PRESIDENT
30 MANAGER
10 CLERK
10 MANAGER
20 ANALYST

9 rows selected.

我们希望按照 EMPNO(类似于您的 ID)对数据进行排序:

SQL> select distinct deptno, job from emp order by empno;
select distinct deptno, job from emp order by empno
*
ERROR at line 1:
ORA-01791: not a SELECTed expression


SQL>

它不会起作用(正如你已经知道的那样)。但是,如果您使用子查询(或 CTE),那么您会得到以下结果:

SQL> with temp as
2 (select min(empno) id, deptno, job
3 from emp
4 group by deptno, job
5 order by 1 desc
6 )
7 select deptno, job
8 From temp
9 order by id desc;

DEPTNO JOB
---------- ---------
10 CLERK
30 CLERK
10 PRESIDENT
20 ANALYST
10 MANAGER
30 MANAGER
20 MANAGER
30 SALESMAN
20 CLERK

9 rows selected.

SQL>

这意味着您的查询可能如下所示:

WITH temp
AS ( SELECT MIN (id) id,
dst_bnk_acnt_id,
dst_cust_id,
org_cust_id,
dst_pos_id,
pmt_typ_cd
FROM tb_cm_t_pmt_coll
WHERE org_pos_id = 8
OR dst_pos_id = 8
OR dst_bnk_acnt_id = 1
GROUP BY dst_bnk_acnt_id,
dst_cust_id,
org_cust_id,
dst_pos_id,
pmt_typ_cd)
SELECT dst_bnk_acnt_id,
dst_cust_id,
org_cust_id,
dst_pos_id,
pmt_typ_cd
FROM temp
ORDER BY id DESC;

关于sql - 如何在oracle中选择不同的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60034842/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com