SQL只能在一对多关系中选择一条记录

时间:2017-05-02 17:37:59

标签: sql sql-server tsql sql-server-2012 left-join

在以下对当前/透视客户的查询中,我需要显示CustomerID,客户的LastName以及显示客户是否已下订单at least的列。 但是,正如预期的那样,如果客户放置了多个订单(一对多关系),它会显示客户的多个记录。 问题:我们如何在每个客户只显示一条记录,因为我们只需要报告客户是否至少下了一个订单?

SELECT c.customerID, o.OrderID, CASE When ISNULL(o.OrderID, 0) = 0 Then 0 Else 
1 End as YesNO
FROM Customers c
LEFT JOIN Orders o
 ON c.customerID = o.customerID

3 个答案:

答案 0 :(得分:2)

使用outer apply()

select 
    c.customerID
  , o.OrderID
  , case when o.OrderID is null then 0 else 1 end as YesNO
from Customers c
  outer apply (
    select top 1 o.OrderID
    from Orders o
    where c.customerID = o.customerID
  ) o

您也可以使用o.OrderId is null代替ISNULL(o.OrderID, 0) = 0

使用group bymin()

select 
    c.customerID
  , min(o.OrderID) as OrderId
  , case when min(o.OrderID) is null then 0 else 1 end as YesNO
from Customers c
  left join Orders o 
    on c.customerID = o.customerID 
group by c.CustomerID  

答案 1 :(得分:0)

使用分组依据。

legend('bottomleft', c("Ovarian Cancer", "Breast Cancer"), 
       lty = c(1:2), col=c("orange","purple"))

答案 2 :(得分:0)

如果您的问题中的描述是可信的,即您想知道客户是否已下订单但不需要代​​表OrderId为每位客户:

select C.CustomerId,
  case when exists ( select 42 from Orders as O where O.CustomerId = C.CustomerId )
    then 1 else 0 end as YesNo
  from Customers as C;

请注意,当您不需要确切的数字时,existscount效率更高。