SQL:我有一个包含多次付款的accnt_num副本的表

时间:2015-07-22 18:41:34

标签: sql

我有两个表,我通过Acct_Num列加入

  • table1有Acct_Num。
  • table2有pmt_cde和Acct_Num。

我的目标是搜索有三(3)个或更多pmt_cde = 536记录的Acct_Num。

这是我的代码:

SELECT  
    Acct_Num, COUNT (*) AS Pmt_cde
FROM tran_hist_dly  AS a
GROUP BY Acct_Num
HAVING COUNT (*) >3
 JOIN ARR_ACCT_DLY AS b
 ON a.Acct_Num = b.Acct_Num;

3 个答案:

答案 0 :(得分:0)

你正在寻找这样的东西:

SELECT ACCOUNT_NUMBER, COUNT(*) AS NUMBER_OF_PAYMENTS FROM PAYMENTS_TABLE
GROUP BY ACCOUNT_NUMBER
HAVING COUNT(*) > 3;

答案 1 :(得分:0)

select ...
from
    (
        SELECT Acct_Num, COUNT(*) AS Payment_Cde
        FROM tran_hist_dly AS a
        GROUP BY Acct_Num
        HAVING COUNT(*) >= 3
    ) as t /* triples */ 
    inner join
    ARR_ACCT_DLY AS aad ON aad.acct_num = t.acct_num

你已经改变了这个问题。以下是获取所需列的方法:

select *
from
    tran_hist_dly as thd
    inner join ARR_ACCT_DLY as aad
        ON aad.acct_num = thd.acct_num
where
        thd.pmt_cde = 536
    and thd.acct_num in (
        select Acct_Num
        from tran_hist_dly
        where pmt_cde = 536
        group by Acct_Num
        having count(*) >= 3
    )

答案 2 :(得分:0)

SELECT a.*, total.Total_Pmt_cde
FROM
    (
        SELECT  
            Acct_Num, COUNT (*) AS Total_Pmt_cde
        FROM tran_hist_dly
        WHERE pmt_cde = 536
        GROUP BY Acct_Num
        HAVING COUNT (*) >= 3
    ) as total INNER JOIN
    ARR_ACCT_DLY AS a ON total.Acct_Num = a.Acct_Num;

尝试这个:

SELECT a.*, t.*
FROM
    tran_hist_dly t INNER JOIN
    ARR_ACCT_DLY AS a ON t.Acct_Num = a.Acct_Num
WHERE exists 
    (
        SELECT  
            COUNT (*) AS Total_Pmt_cde
        FROM tran_hist_dly th
        WHERE th.pmt_cde = 536
        AND   th.Acct_Num = t.Acct_Num 
        HAVING COUNT (*) >= 3
    )