尝试以下操作:
Select Customer From
(
Select Customer,Store from TableName group by Store,Customer
)tbl
Group By Customer Having COUNT(Customer)>=2 Order By Customer
编辑:
Declare @MainTable table
(
Customer varchar(222),Store varchar(2222)
)
Insert Into @MainTable
Select 'C1','X'
Union All
Select 'C1','Y'
Union All
Select 'C1','X'
Union All
Select 'C2','X'
Union All
Select 'C2','Y'
Union All
Select 'C2','Z'
Union All
Select 'C3','X'
Union All
Select 'C3','Z'
Union All
Select 'C4','X'
Union All
Select 'C4','Y'
Declare @temp table
(
Customer varchar(200)
)
Insert Into @temp
Select Customer From
(
Select Customer,Store from @MainTable group by Store,Customer
)tbl
Group By Customer Having COUNT(Customer)>=2 Order By Customer
Declare @Customer_Store table
(
Customer varchar(200),
Stores varchar(200)
)
DECLARE @Stores varchar(10)
Declare @Customer varchar(256)
While((Select COUNT(*) From @temp)>0)
Begin
Set @Customer=(Select Top 1 Customer From @temp)
Select @Stores=coalesce(@Stores + ',','') + Store From
@MainTable Where Customer=@Customer
Group By Store
Order By Store
Insert Into @Customer_Store Select @Customer,@Stores
Delete From @temp Where Customer=@Customer
Set @Stores=null
End
Select Cast(COUNT(Customer) as Varchar(5))+' Customers shopped at Store ('+Stores+')' CustomerDetail From @Customer_Store
Group By Stores
输出:
2 Customers shopped at Store (X,Y)
1 Customers shopped at Store (X,Y,Z)
1 Customers shopped at Store (X,Z)