briangriffin
Programmer
I've read the FAQ and other posts regarding concatenating fields into a long string, but something isn't quite right when I try. Using the AdventureWorks db, I want a listing of each sales territory and then one field listing each salesperson in that territory:
I'm getting a list of territories, but only one salesman from each - where did I go wrong? (I'm not concerned with the sales total field right now).
Thanks.
Code:
declare @v_sales table
(territoryID int ,
territory varchar(15),
salesmen varchar(255))
insert into @v_sales (territoryID,territory, salesmen)
select TerritoryID, Name,''
from Sales.SalesTerritory
order by 1
declare @v_salesmen table
(territoryID int,
salesperson varchar(40),
sales numeric(20,2))
insert into @v_salesmen
select
c.TerritoryID,
d.FirstName + ' ' + d.LastName,
a.SalesYTD
from Sales.SalesPerson a INNER JOIN HumanResources.Employee b
on b.EmployeeID = a.SalesPersonID
LEFT OUTER JOIN Sales.SalesTerritory c
on c.TerritoryID = a.TerritoryID
INNER JOIN Person.Contact AS d
on d.ContactID = b.ContactID
order by 1
Declare @min int, @max int
Select @min = 1, @max = Max(TerritoryID)
From @v_sales
While @min <= @max
Begin
Update @v_sales
Set salesmen = salesmen + b.salesperson + ' '
From @v_sales a inner join @v_salesmen b
ON a.territoryID = b.territoryID
Where a.territoryID = @min
Select @min = @min + 1
End
select * from @v_sales
I'm getting a list of territories, but only one salesman from each - where did I go wrong? (I'm not concerned with the sales total field right now).
Thanks.