2

我有一个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' 

它给出了 0 个结果oracle SQL Developer

如何从这里开始?

4

3 回答 3

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)
于 2013-03-06T04:50:28.297 回答
0

按客户从表名组中选择不同的客户,商店的数量(商店)> 2

对不起....你可以试试这样

“选择客户,按客户从 table_name 组中存储,存储计数(客户)>=1 客户 asc 的订单”

我希望这是正确的。

于 2013-03-06T05:07:06.037 回答
0

我认为你应该在 MySQL 中使用类似GROUP_CONCAT的东西。

在这里您可以找到如何在 Oracle 中模拟它

例如,对于 Oracle 11g R2,您可以使用 LISTAGG:

SQLFiddle 演示

SELECT customer, 
       LISTAGG(store, ',') WITHIN GROUP (ORDER BY store) 
       AS STORES
FROM   
(select distinct customer,store from t) t1
GROUP BY customer;
于 2013-03-06T07:23:10.950 回答