[英]SQL Query to Retrieve data by comparing column name to a particular string
I have a SQL
Table consisting of customer, transaction and store. 我有一个由客户,交易和商店组成的
SQL
表。 Store has 3 values (X,Y,Z) 商店有3个值(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). 但是,现在我想要在(X,Y)(Y,Z)(Z,X)和(X,Y,Z)2家商店购物的客户详细信息。
When I use 当我使用
select distinct customer from TABLE where store='X'
it gives 0 results in oracle SQL Developer
它在
oracle SQL Developer
给出0个结果
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 按客户从表名组中选择不同的客户,计数(商店)> 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" “选择客户,从表名组中按客户选择商店,计数(客户)> = 1个订单的商店按客户asc排序”
i hope this is correct. 我希望这是正确的。
I think you should use something like GROUP_CONCAT in MySQL. 我认为您应该在MySQL中使用类似GROUP_CONCAT的名称。
Here you can find how you can emulate it in Oracle 在这里,您可以找到如何在Oracle中进行仿真
For example for Oracle 11g R2 you can use LISTAGG: 例如,对于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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.