我试图对一个表中的结果进行计数,然后将计数的总数插入同一表的一个字段中,但是我得到的总数是针对整个表而不是特定的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)
答案 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;