简体   繁体   English

选择至少具有P和R的数据

[英]select data that has at least P and R

I have a table named Table1 as shown below: 我有一个名为Table1的表,如下所示:

ID  AccountNo     Trn_cd
1   123456           P
2   123456           R
3   123456           P
4   12345            P
5   111              R
6   111              R
7   5625             P

I would like to display those records that accountNo appears more than one time (duplicate) and trn_cd has at least both P and R. 我想显示accountNo出现多次(重复)且trn_cd至少具有P和R的那些记录。

In this case the output should be at this way: 在这种情况下,输出应采用以下方式:

ID  AccountNo     Trn_cd
1   123456           P
2   123456           R
3   123456           P

I have done this sql but not the result i want: 我已经完成了此sql,但没有得到我想要的结果:

select * from Table1 
where AccountNo IN 
(select accountno from table1 
where trn_cd = 'P' or trn_cd = 'R' 
group by AccountNo having count(*) > 1) 

Result as below which AccountNo 111 shouldn't appear because there is no trn_cd P for 111: 结果如下,由于没有111的trn_cd P,因此不会出现AccountNo 111:

ID  AccountNo   Trn_cd
1   123456        P
2   123456        R
3   123456        P
5   111           R
6   111           R

Any idea? 任何想法?

Use aggregation for this. 为此使用聚合。 To get the account numbers: 要获取帐号:

select accountNo
from table1
having count(*) > 1 and
       sum(case when trn_cd = 'P' then 1 else 0 end) > 0 and
       sum(case when trn_cd = 'N' then 1 else 0 end) > 0

To get the account information, use a join or in statement: 要获取帐户信息,请使用joinin语句:

select t.*
from table1 t
where t.accountno in (select accountNo
                      from table1
                      having count(*) > 1 and
                             sum(case when trn_cd = 'P' then 1 else 0 end) > 0 and
                             sum(case when trn_cd = 'N' then 1 else 0 end) > 0
                     )

This problem is called Relational Division . 这个问题称为Relational Division

This can be solved by filtering the records which contains P and R and counting the records for every AccountNo returned, and filtering it again using COUNT(DISTINCT Trn_CD) = 2 . 可以通过过滤包含PR的记录并计数返回的每个AccountNo的记录,然后使用COUNT(DISTINCT Trn_CD) = 2再次对其进行过滤来COUNT(DISTINCT Trn_CD) = 2

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  AccountNo
            FROM    TableName
            WHERE   Trn_CD IN ('P','R')
            GROUP   BY AccountNo
            HAVING  COUNT(DISTINCT Trn_CD) = 2
        ) b ON a.AccountNO = b.AccountNo

OUTPUT 输出值

╔════╦═══════════╦════════╗
║ ID ║ ACCOUNTNO ║ TRN_CD ║
╠════╬═══════════╬════════╣
║  1 ║    123456 ║ P      ║
║  2 ║    123456 ║ R      ║
║  3 ║    123456 ║ P      ║
╚════╩═══════════╩════════╝

For faster performance, add an INDEX on column AccountNo . 为了提高性能,请在AccountNo列上添加一个INDEX

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM