我一直在努力进行此查询,这就是我所需要的:
两个表,表A和表B,对于表A中的每一行,表B中可能有N行。但是我需要从A中找到在B中正好有两行的行,其中之一是type( B中的列)以“ PYT”开头,另一个列为null,我也需要表B中的金额来自最新行(表B中的DATEP),但我一直在尝试这样做,但是我我发现了一些问题,这是我到目前为止的问题:
SELECT
A.TYPE, A.NMRAD,A.ID, B.AMOUNT
FROM
TABLE_A A
JOIN TABLE_B B ON A.ID = B.ID_A AND A.NMRAD = B.NMRAD AND A.TYPE = B.TYPE
WHERE
(SELECT COUNT(1) FROM (SELECT 1 FROM TABLE_B WHERE ID_A = A.ID AND TYPE LIKE 'PYT%'
UNION
SELECT 1 FROM TABLE_B WHERE ID_A = A.ID AND B.TYPEPROCESS IS NOT NULL))=2
WHERE A.TYPE=?
例如:
Table A
ID | NMRAD | TYPE
1 | 2 | PYT1
2 | 14 | PYT2
5 | 11 | PYY2
TABLE B
ID_A | NMRAD | TYPE | TYPEPROCESS | AMOUNT | DATEP
1 | 2 | PTY1 | NULL | 50 | 18/10/2018
1 | 2 | PYY2 | 123 | 35 | 19/10/2018
2 | 14 | PTY2 | NULL | 50 | 18/09/2018
2 | 14 | PTY2 | NULL | 35 | 17/10/2018
2 | 14 | PTY3 | NULL | 77 | 11/07/2018
EXPECTED RESULT
TYPE | NMRAD | ID | AMOUNT
PTY1 | 2 | 1 | 35
答案 0 :(得分:0)
我无法匹配您的“恰好两行”条件,但这是与您的预期结果匹配的SQL:
WITH
aset AS
(SELECT a.*
FROM tablea a
WHERE EXISTS
(SELECT NULL
FROM tableb b
WHERE a.id = b.id
AND a.nmrad = b.nmrad
AND a.TYPE = b.TYPE
AND b.TYPE LIKE 'PTY%')
AND EXISTS
(SELECT NULL
FROM tableb b
WHERE a.id = b.id
AND a.nmrad = b.nmrad
AND a.TYPE = b.TYPE
AND b.typeprocess IS NULL))
SELECT a.*
, (SELECT amount
FROM tableb b
WHERE a.id = b.id
AND a.nmrad = b.nmrad
AND datep = (SELECT MAX( datep )
FROM tableb bb
WHERE b.id = bb.id AND b.nmrad = bb.nmrad)) amount
FROM aset a;
结果是:
ID NMRAD TYPE AMOUNT
1 2 PTY1 35
让我们轻松为您提供帮助,下一次提供设置:
CREATE TABLE tablea
(
id NUMBER( 3 )
, nmrad NUMBER( 2 )
, TYPE VARCHAR2( 4 )
);
CREATE TABLE tableb
(
id NUMBER( 3 )
, nmrad NUMBER( 2 )
, TYPE VARCHAR2( 4 )
, typeprocess NUMBER( 3 )
, amount NUMBER( 3 )
, datep DATE
);
begin
insert into tablea values (1, 2, 'PTY1');
insert into tablea values (2, 14, 'PTY1');
insert into tablea values (5, 11, 'PTY1');
insert into tableb values (1, 2, 'PTY1', NULL, 50, to_date('18/10/2018', 'DD/MM/YYYY'));
insert into tableb values (1, 2, 'PYY2', 123, 35, to_date('19/10/2018', 'DD/MM/YYYY'));
insert into tableb values (2, 14, 'PTY2', NULL, 50, to_date('18/09/2018', 'DD/MM/YYYY'));
insert into tableb values (2, 14, 'PTY2', NULL, 35, to_date('17/10/2018', 'DD/MM/YYYY'));
insert into tableb values (2, 14, 'PTY3', NULL, 77, to_date('11/07/2018', 'DD/MM/YYYY'));
commit;
end;