【问题标题】:Display the names of customers who ordered the same set of products as customers from Brazil显示与巴西客户订购同一组产品的客户名称
【发布时间】:2018-11-05 14:32:01
【问题描述】:

Microsoft Sql Server 2017,Northwind 数据库。

大家好,我还在尝试在sql server中做这些问题,但是我堆叠了,我不知道该怎么做。请给我一些提示,如何咬它:P

select *     
from

(select companyname, products.productid, productname,[Order Details].OrderID
    from [order details], orders, customers, products
    where [order details].orderid=orders.orderid AND
          orders.customerid=customers.customerid AND
          [order details].productid=products.productid) c1
    inner join
    (select companyname, products.productid, productname, [Order Details].OrderID
    from [order details], orders, customers, products
    where [order details].orderid=orders.orderid AND
          orders.customerid=customers.customerid AND
          [order details].productid=products.productid  AND
          Customers.Country='Brazil') c2
          on c1.productId=c2.productId and c1.productname=c2.productname

【问题讨论】:

  • 您应该从学习 ANSI-92 样式连接开始。它们已经上市超过 25 年了。 sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins 对于手头的问题,我不太确定您要完成什么。
  • 好的,我会阅读链接 :) 我必须显示订购同一组产品的客户,就像来自巴西的客户一样,所以我必须以某种方式比较两个选择并显示公司名称.
  • 我建议也使用一些别名。 :)

标签: sql sql-server northwind


【解决方案1】:

我不确定巴西的客户是否应该从结果数据中排除,但要为您指明正确的方向,请考虑以下查询:

select c.*
from
    (
        select distinct o.productid
        from [order details] o inner join customers c
        on o.customerid = c.customerid
        where c.country = 'Brazil'
    ) p
    inner join [order details] o on p.productid = o.productid
    inner join customers c on o.customerid = c.customerid

在这里,嵌套选择获得了巴西客户购买的一组不同的产品。然后将此选择的结果连接到您的order details 表中,以获取所有购买此类产品的客户(这将包括巴西人)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多