【问题标题】:SQL query report indicating no salesSQL查询报告显示没有销售
【发布时间】:2017-03-13 18:38:22
【问题描述】:

您好,有帮助的 Stack Overflow 社区 - 我在试图弄清楚我正在处理的这个查询时遇到了一些麻烦。它可能看起来很简单,希望如此,但我现在只是在学习。我的查询应该提供一个列表,显示哪些客户没有任何订单?包括联系信息,以便销售部门可以跟进这些客户。非常感谢任何帮助,在此先感谢!

select c.CustomerID 'Customer ID', c.CompanyName 'Company Name',
c.ContactName 'Contact Name', c.Address, c.City, 
c.StateOrRegion 'State Or Region', c.PostalCode 'Postal Code',
c.Country, c.Phone, c.Fax, o.OrderID 'Order ID', 
o.ShippedDate 'Shipped Date' 
from orders o 
left join Customers c 
on o.customerid = c.customerid
where o.shippeddate is not null
order by c.ContactTitle asc

再次感谢您抽出宝贵时间提供帮助!

【问题讨论】:

  • 我已删除不兼容的数据库标签 - 请标记您实际使用的数据库。
  • right join 而不是 left join 并将 o.shippeddate is not null 更改为 o.shippeddate is null 你是当前的逻辑说。退回所有已发货的订单和相关客户。您想要的是退回所有尚未发货的客户。

标签: sql


【解决方案1】:

您的餐桌顺序倒退,您的is not null 应该是is null 以查找没有orderscustomers

或者您可以将您的left join 更改为right join,但仍将is not null 更改为is null

select c.CustomerID 'Customer ID', c.CompanyName 'Company Name',
  c.ContactName 'Contact Name', c.Address, c.City, 
  c.StateOrRegion 'State Or Region', c.PostalCode 'Postal Code',
  c.Country, c.Phone, c.Fax, o.OrderID 'Order ID', 
  o.ShippedDate 'Shipped Date' 
from Customers c 
  left join orders o 
    on o.customerid = c.customerid
where o.shippeddate is null
order by c.ContactTitle asc

【讨论】:

    【解决方案2】:

    我会简单地使用not exists:

    select c.*
    from customers c
    where not exists (select 1
                      from orders o
                      where o.customerid = c.customerid
                     )
    order by c.ContactTitle asc;
    

    此外,您不应该对列别名使用单引号。它们只能用于字符串和日期常量。

    对于不存在的订单,绝对不需要包含订单信息。我将select * 用作速记,而不是列出您可能想要的列。

    【讨论】:

    • 感谢@Gordon Linoff 和 SqlZim 的帮助和教育 - 谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2015-09-16
    相关资源
    最近更新 更多