SQL:计算重复项时的行数

时间:2014-07-30 22:32:32

标签: sql sql-server

我有一个相当容易的问题,我无法解决。我有两个表,一个帐户表和一个客户表。帐户表中的每一行都是唯一的,但有多个客户可以与帐户ID相关联。例如,帐户ID 101与客户表中的id 1和2相关联。

我想要做的是加入两个表,以便我可以计算给定日期期间帐户表中的行数。但是,我还想只选择客户表中cust值为A的那些帐户。所以我需要加入这两个表,我正在努力梳理连接和不同方面。

Acct table = 
account    ...
101          ...
102          ...
103          ...
104          ...
105          ...

Customer table = 
id          prim_acct     cust
1               101           A
1               101           A
2               102           A    
3               103           A    
3               103           A
3               103           A
4               104           R
5               105           R

我尝试过的一些不连贯的事情。由于数据太大,我只是尝试使用前10名并获得计数,我可以将每个帐户隔离到1。

;with CTE as
( 
  SELECT TOP 10 * FROM dbo.CL_CUSTOMER AS cus
  WHERE cus.CUSTOMER_STATUS = 'A'
) 
SELECT ac.ACCOUNT_NUMBER, COUNT(*) AS ac
GROUP BY ac.ACCOUNT_NUMBER FROM CTE;


SELECT TOP 10 cus.PRIMARY_ACCOUNT_NUMBER, COUNT(*) FROM dbo.CL_ACCOUNT AS ac 
INNER JOIN (SELECT DISTINCT ACCOUNT_NUMBER FROM dbo.CL_CUSTOMER WHERE CUSTOMER_STATUS = 'A') 
                dbo.CL_CUSTOMER AS cus ON ac.ACCOUNT_NUMBER = cus.PRIMARY_ACCOUNT_NUMBER
GROUP BY cus.PRIMARY_ACCOUNT_NUMBER
HAVING COUNT(*) >= 2;

1 个答案:

答案 0 :(得分:1)

我认为你正在尝试这样做:

select count(distinct a.account)
from account a join
     customer c
     on a.account = c.prim_acct
where c.cust_value = 'A' and
      a.thedate between @date1 and @date2;

您也可以将其标记为exists个查询。这样,您就不需要count(distinct)

select count(a.account)
from account a 
where exists (select 1
              from customer c
              where a.account = c.prim_acct and c.cust_value = 'A'
             ) and
      a.thedate between @date1 and @date2;