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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Query

Author  Topic 

dewacorp.alliances

452 Posts

Posted - 2009-12-10 : 19:54:59
Hi there

I have 3 tables: Customer, CustomerTypes, CustomerCustomerTypes. CustomerCustomerTypes is basically is a bridge table between the Customer and CustomerTypes.

Table structure:
Customers:
CustomerID
CustomerName

CustomerTypes:
CustomerTypeID
CusctomerTypeName

CustomerCustomerTypeID
CustomerID
CustomerTypeID

Sample Data:
Customers:
1, ABC
2, CBA

CustomerTypes:
1, Broadcast
2, Banking
3, Retailer

CustomerCustomerTypes:
1, 1
2, 2
2, 3


I want to be able to return query as follow:

ABC; "Broadcasting"
CustomerCustomerTypes; "Banking, Retailer"

as well as to be able to search that string let say "CustomerTypeID = 2"

It will be ruturned as :
CustomerCustomerTypes; "Banking, Retailer"

I can do this cursor type of query BUT i am just wondering maybe there is a better way.

Thanks


RyanRandall
Master Smack Fu Yak Hacker

1074 Posts

Posted - 2009-12-11 : 07:46:49
This?

declare @Customers Table (CustomerID int, CustomerName varchar(50))
insert @Customers
select 1, 'ABC'
union all select 2, 'CBA'

declare @CustomerTypes table (CustomerTypeID int, CustomerTypeName varchar(50))
insert @CustomerTypes
select 1, 'Broadcast'
union all select 2, 'Banking'
union all select 3, 'Retailer'

declare @CustomerCustomerTypes table (CustomerID int, CustomerTypeID int)
insert @CustomerCustomerTypes
select 1, 1
union all select 2, 2
union all select 2, 3

; with t1 as (
select a.*, b.CustomerName, c.CustomerTypeName
from @CustomerCustomerTypes a
inner join @Customers b on a.CustomerID = b.CustomerID
inner join @CustomerTypes c on a.CustomerTypeID = c.CustomerTypeID)
select CustomerId, CustomerName,
stuff((select ', ' + CustomerTypeName from t1 where CustomerId = a.CustomerId
for xml path('')),1,2,'') as CustomerCustomerTypes
from t1 a
--where CustomerTypeId = 2 --uncomment this to filter
group by CustomerId, CustomerName


Ryan Randall - Yak of all trades
Solutions are easy. Understanding the problem, now, that's the hard part.
Go to Top of Page
   

- Advertisement -