编写一个SQL查询,查询客户只拥有一个商店的所有订单

编写一个SQL查询,查询客户只拥有一个商店的所有订单,sql,Sql,我有以下关系方案: 店铺Id、店铺名称 玩具ID、名称 CustomerCustomer ID、名称 订单ID,客户ID Olines订单ID、商店ID、玩具ID 我想用SQL编写一个查询,以查找所有客户的客户Id,这些客户的所有订单都只在一个商店中,而该商店不能是“玩具反斗城” 我是SQL新手,不知道该怎么做。任何帮助都将不胜感激 这可能会对你有所帮助。只需按照已有的替换表名和列名即可 select a.customerid from ( select or.customerid,s

我有以下关系方案:

店铺Id、店铺名称 玩具ID、名称 CustomerCustomer ID、名称 订单ID,客户ID Olines订单ID、商店ID、玩具ID 我想用SQL编写一个查询,以查找所有客户的客户Id,这些客户的所有订单都只在一个商店中,而该商店不能是“玩具反斗城”


我是SQL新手,不知道该怎么做。任何帮助都将不胜感激

这可能会对你有所帮助。只需按照已有的替换表名和列名即可

select a.customerid 
from (
    select or.customerid,st.storeid,count(*) count 
    from Order or, Onlines on, Store st 
    where or.orderid=on.orderid and on.storeid=st.storeid and st.store_name!='Toy R Us' 
    group by or.customerid,st.storeid) a 
where a.count=1;

这可能对你有帮助。只需按照已有的替换表名和列名即可

select a.customerid 
from (
    select or.customerid,st.storeid,count(*) count 
    from Order or, Onlines on, Store st 
    where or.orderid=on.orderid and on.storeid=st.storeid and st.store_name!='Toy R Us' 
    group by or.customerid,st.storeid) a 
where a.count=1;

您可以为此使用exists子句

; With cte as(
Select distinct name , c.[Customer ID],s.[store Id] 
From customer c  join order o
On c.[Customer ID]=o.[Customer ID]
Join olines l
On o.[order ID]=l.[order ID]
Join store s
On s.[store Id]=l.[store Id] and not s.[store_name]='Toys R Us')

Select * 
from cte c1 
where
 not exists(
 Select 1 
 from cte c2 
 where c2.[Customer ID]=c1.[Customer ID] and c2.[store Id]=<>c1.[store Id] 
 )

您可以为此使用exists子句

; With cte as(
Select distinct name , c.[Customer ID],s.[store Id] 
From customer c  join order o
On c.[Customer ID]=o.[Customer ID]
Join olines l
On o.[order ID]=l.[order ID]
Join store s
On s.[store Id]=l.[store Id] and not s.[store_name]='Toys R Us')

Select * 
from cte c1 
where
 not exists(
 Select 1 
 from cte c2 
 where c2.[Customer ID]=c1.[Customer ID] and c2.[store Id]=<>c1.[store Id] 
 )

请共享示例数据,查询您尝试和想要的输出您必须连接表,对它们进行分组,并通过使用条款进行限制请释放您的问题,并根据该数据添加一些和预期的输出。请您的问题-请勿在评论中发布代码或其他信息。请共享示例数据,查询您尝试和期望的输出您必须加入表,对它们进行分组,并通过使用条款进行限制请释放您的问题,并根据该数据添加一些和期望的输出。请您的问题-不要在评论中发布代码或附加信息。