2015-06-01 170 views
0

我正在使用SQL Server 2012.我有一個表CustomerMaster。下面是一些示例內容:SQL Server 2012計數

+--------+---------------+-----------------+-------------+ 
| CustNo | NewMainCustNo | Longname  | NoOfMembers | 
+--------+---------------+-----------------+-------------+ 
| 3653 | 3653   | GroupId:003  |    | 
| 3654 | 3654   | GroupId:004  |    | 
| 11  | 3653   | Peter Evans  |    | 
| 155 | 3653   | Harold Charley |    | 
| 156 | 3654   | David Arnold |    | 
| 160 | 3653   | Mickey Willson |    | 
| 2861 | 3653   | Jonathan Wickey |    | 
| 2871 | 3653   | William Jason |    | 
+--------+---------------+-----------------+-------------+ 

NewMainCustNo爲客戶記錄相當於CustNo從組記錄。基本上每個客戶都屬於一個特定的羣體。

我的問題是如何更新組記錄的NoOfMembers列,其客戶總數屬於某個組。

請分享你的想法如何做到這一點。

謝謝......

回答

1

這是我想出了

update CustomerMaster 
set NoOfMembers = (select count(*) from CustomerMaster m2 where m2.NewMainCustNo = CustomerMaster.CustNo and m2.CustNo <> CustomerMaster.CustNo) 
where LongName like 'GroupId:%' 

檢查this SQL Fiddle解決方案在行動中看到的查詢。

但我不同意你的數據結構。你應該有一個單獨的表爲你的組。在客戶表中,您只需引用組表中的組的ID。這使得所有內容(包括上面的查詢)變得更清潔。

+0

非常感謝它的工作... –

+0

是的我知道你的意思,但它更容易有一個表中的所有數據遷移目的。這些不是活的數據庫內容。這些是DM目的所需的數據。謝謝大家的支持。 –

0

如果我理解正確,可以使用窗口函數進行更新。下面是可更新的CTE的例子:

with toupdate as (
     select cm.*, count(*) over (partition by NewMainCustNo) as grpcount 
     from customermaster 
    ) 
update toupdate 
    set NoOfMembers = grpcount; 
+0

謝謝戈登,但它也計算組記錄。我想要的是屬於不包括組記錄的組的成員數量。有什麼建議麼? –

+0

@Devinda。 。 。你能減1嗎? –

+0

嗨戈登,不,我沒有嘗試減1,我會盡力讓你知道男人。許多thanx爲您的支持,歡呼聲;-) –

0

您可能沒有選擇這樣做,但我會將組分離到自己的表中。

create table Groups (
     GroupID int primary key, 
     Name varchar(200) 
    ) 

然後,NewMainCustNo更改爲羣ID,創建,清除組的客戶表,並從那裏走。然後,得到一個組數將是:

select GroupID, 
     Name [Group Name], 
     COUNT(*) 
    from Groups g 
    join Customers c on 
     c.GroupID = g.GroupID