与另一个字段的条件匹配的SQL计数字段

时间:2015-10-01 19:35:03

标签: sql-server ssms

我有一个与帐号ID相关联的帐号字段。 如何获得使用帐号支付的所有ID的总数(并将新列添加到我的临时表中。

for the sake of sanity
ID = ID
ACCOUNT NUMBER = ACCT
COUNT = COUNT (NEW COLUMN) 

ID |ACCOUNT NUMBER (GIVEN)   
1  |123           
1  |124           
2  |125           
3  |126           
3  |127           
3  |128           
3  |129           
4  |130           
5  |131           
5  |132           
5  |133           
5  |134           
5  |135           
5  |136           
5  |137           


ID |ACCOUNT NUMBER|COUNT  
1  |123           |2     
1  |124           |2     
2  |125           |1     
3  |126           |3     
3  |127           |3     
3  |128           |3     
3  |129           |3     
4  |130           |1     
5  |131           |7     
5  |132           |7     
5  |133           |7     
5  |134           |7     
5  |135           |7     
5  |136           |7     
5  |137           |7     

2 个答案:

答案 0 :(得分:1)

您需要使用窗口函数。

COUNT([Account Number]) OVER (PARTITION BY [ID])

修改

这应该有助于排除任何一个计数。

SELECT *
FROM (
  SELECT ID, ACCT, COUNT(ACCT) OVER (PARTITION BY ID) AS [Count]
  FROM my_table) x
WHERE x.[Count] > 1

答案 1 :(得分:0)

使用AnyObject

的解决方案
group by