我有一个SQL
表,包含客户,交易和商店。商店有3个值(X,Y,Z)
我想检索在特定商店购物的顾客,所以我使用了这个查询
select distinct customer from TABLE group by store.
但是,现在我想要在2个商店(X,Y)(Y,Z)(Z,X)以及(X,Y,Z)购物的顾客详情。
当我使用
时select distinct customer from TABLE where store='X'
它在oracle SQL Developer
如何从这里开始?
答案 0 :(得分:1)
请尝试以下操作:
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)
答案 1 :(得分:0)
按客户从表名组中选择不同的客户,存储有计数(商店)> 2
抱歉....你可以这样试试“选择客户,按客户存储table_name组,存储计数(客户)> =客户asc订购1个”
我希望这是正确的。
答案 2 :(得分:0)
我认为你应该在MySQL中使用类似GROUP_CONCAT的东西。
Here you can find how you can emulate it in Oracle
例如,对于Oracle 11g R2,您可以使用LISTAGG:
SELECT customer,
LISTAGG(store, ',') WITHIN GROUP (ORDER BY store)
AS STORES
FROM
(select distinct customer,store from t) t1
GROUP BY customer;