2011-10-20 65 views
1

我正在嘗試做一個簡單的查詢來計算客戶端被代理調用的次數。MySQl統計計數與組

Call_ID | Lead_id | Agent 
1  | 1  | madison 
2  | 1  | Kelly 
3  | 2  | madison 
4  | 1  | Sam 

我需要添加一個名爲call_attempt另一列這將是唯一的每個代理,並導致

Call_ID | Lead_id | Agent | call attempt 
1  | 1  | madison | 1 
2  | 1  | Kelly | 2 
3  | 2  | madison | 1 
4  | 1  | Sam  | 3 
+0

這是否只需要進行一次填充到表中,或是否需要每一個表中的記錄被修改的時間進行更新? – mellamokb

回答

0

與醜惡表演的查詢,但在這裏,你無論如何是:

select t1.call_id, t1.lead_id, t1.agent, 
     (select count(*) from THETABLE t2 
     where t2.lead_id=t1.lead_id 
      and t2.call_id <= t1.call_id) 
from THETABLE t1 

UPDATE:

具有增強性能的查詢:

select t1.call_id, t1.lead_id, t1.agent, 
     count(t2.call_id) as cum_sum 
from THETABLE t1 
inner join THETABLE t2 
    on t2.lead_id=t1.lead_id 
    and t2.call_id <= t1.call_id 
group by t1.call_id 
+0

(更新......) – MarianP

+0

這是贏家! – Val

0

對於你的問題上半年:

SELECT Lead_id, Agent, COUNT(*) AS NumberOfCalls 
    FROM YourTable 
    GROUP BY Lead_id, Agent 

對於下半年,我不確定你在問什麼。

+0

這聽起來像OP希望'call attempt'列是'Lead_id'上的一個排序/排序,它需要計算並更新回表中。 – mellamokb

+0

匿名downvoter會照顧解釋他們的反對意見嗎? –

+1

@mellamokb如果這是OP所要做的,我會阻止他們嘗試將這種數據直接存儲在表中。爲了保持更新,它變得非常頭疼。 –

1

你可以指望的呼叫數量通過之前在表中出現的lead_id來計算排名,並用查詢更新到新的call_attempt字段中像下面這樣:

update calls c 
    set call_attempt = 
     (select count(Lead_id) from calls c2 
     where c.Lead_id = c2.Lead_id and c2.Call_ID <= c.Call_ID); 

這裏是一個demontsration:http://sqlize.com/fXn4p2cc5j