I have a SQL
Table consisting of customer, transaction and store. Store has 3 values (X,Y,Z)
I want to retrieve customers who shopped at particular store, so I used this query
select distinct customer from TABLE group by store.
However, now I want the customer details who shopped at 2 stores (X,Y) (Y,Z) (Z,X) and also (X,Y,Z).
When I use
select distinct customer from TABLE where store='X'
it gives 0 results in oracle SQL Developer
How to proceed from here?
Try following:
Select Customer From
(
Select Customer,Store from TableName group by Store,Customer
)tbl
Group By Customer Having COUNT(Customer)>=2 Order By Customer
Edit:
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
Output:
2 Customers shopped at Store (X,Y)
1 Customers shopped at Store (X,Y,Z)
1 Customers shopped at Store (X,Z)
select distinct customer from tablename group by customer ,store having count(stores)>2
sorry....you can try like this
"select customer,store from table_name group by customer ,store having count(customer)>=1 order by customer asc"
i hope this is correct.
I think you should use something like GROUP_CONCAT in MySQL.
Here you can find how you can emulate it in Oracle
For example for Oracle 11g R2 you can use LISTAGG:
SELECT customer,
LISTAGG(store, ',') WITHIN GROUP (ORDER BY store)
AS STORES
FROM
(select distinct customer,store from t) t1
GROUP BY customer;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.