将DISTINCT值的计数插入同一表

时间:2018-08-21 13:59:45

标签: sql sql-server

我试图对一个表中的结果进行计数,然后将计数的总数插入同一表的一个字段中,但是我得到的总数是针对整个表而不是特定的ID

以下是一些示例数据:

Id  Customer    Invoice#    Count of Invoice
22  12345       6789        
23  777         11223       
24  777         11223
25  777         2341

我需要计算每位客户出现DISTINCT Invoice#的次数,然后将该值放入该客户每一行的Invoice Count字段中,例如,鉴于第一行中的Count of Invoice应该为1并在接下来的3行中添加2个。

我有这个,但它似乎可以计算表中所有DISTINCT Invoice#的总数,并在每行中输入相同的值。

UPDATE [Insight].[dbo].[Rev]
SET [Count of Invoice] = 
(SELECT COUNT(DISTINCT [Invoice#])
  FROM [Insight].[dbo].[Rev]
WHERE Customer = Customer)

2 个答案:

答案 0 :(得分:2)

您需要alias

UPDATE r
   SET r.[Count of Invoice] = (SELECT COUNT(DISTINCT r1.[Invoice#])
                               FROM [Insight].[dbo].[Rev] r1
                               WHERE r.Customer = r1.Customer)
FROM [Insight].[dbo].[Rev] r;

答案 1 :(得分:1)

子查询中的

Customer = Customer将针对子查询表进行解析;实际上意味着它将对行解析为true(除非Customer的值为NULL)。这应该起作用:

UPDATE R
SET [Count of Invoice] = DC.DistinctCount
FROM [Insight].[dbo].[Rev] R
     CROSS APPLY (SELECT COUNT(DISTINCT ca.[Invoice#]) AS DistinctCount
                  FROM [Insight].[dbo].[Rev] ca
                  WHERE ca.Customer = R.Customer) DC;