Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
akpaga
Constraint Violating Yak Guru
331 Posts |
Posted - 2011-08-01 : 14:56:52
|
Hi all,I have a table Csutomer with following fieldsCustomer_no Customer_name, Agent_no1,X, 12,Y,23,Z,24,A,3agent tableagent_no,agent_name1,james2,Jack3,Jill4,Jenhow to loop through this table and find out if the the every agent has equal no of customersin this case agent_no =2 has two customers but agent-no 4 Jen has no customer then the count should be 1but for example agent 4 is not at there in agent table then the count should be 2 since agent no 1 and agent_no 3 have only one ticket where as agent_no 2 has two ticketsi need the coumt as 2 (agent no1 and agent_no 3 for assigning any tickets to them)The reason i doing this is when a new customer 5 is comes in the customer tablei have to check the agents table for any free agent by checking the agent_no field to the agent_no field customer table ..If all customers have a customer atleast the i hav eto assign the customer to the agent having least customers... |
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2011-08-01 : 19:37:00
|
Here's a startDECLARE @customers Table (id int,Customer varchar(1),Agent int) INSERT INTO @customersSELECT 1,'X', 1 UNIONSELECT 2,'Y',2 UNIONSELECT 3,'Z',2 UNIONSELECT 4,'A',3 Declare @agents Table (id int,agent varchar(10))Insert into @agentsselect 1,'james' unionselect 2,'Jack' unionselect 3,'Jill' unionselect 4,'Jen'select a.agent,a.id,count(c.agent) as Customersfrom @agents aleft join @customers c on a.id = c.agentgroup by a.agent,a.idorder by customersJimEveryday I learn something that somebody else already knew |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-08-02 : 01:14:47
|
for getting agent with least customers isnt it enough to do like this?SELECT TOP 1 WITH TIES a.agent_no,a.agent_nameFROM agent aINNER JOIN (select agent_no,COUNT(*) as custcnt FROM Customer GROUP BY agent_no)cON c.agent_no = a.agent_noORDER BY custcnt ASC ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|