查询返回不需要的结果

时间:2015-09-18 15:12:51

标签: sql sql-server

我有2张桌子" Dispatch"和"销售"包含关系列Invoice。 " SalesLed"有多个与1个特定发票号相关的记录。 Dispatch只有1个结果。我需要查询只有当Spiff的所有匹配项都在" Salesled"是零。否则,我不想看到那张发票。

基本查询:

SELECT invoice,dispatch
  FROM dispatch
 WHERE Invoice=0000001071

enter image description here

SELECT invoice,spiff
  FROM salesled
 WHERE Invoice=0000001071

enter image description here

不受欢迎的结果:它会返回包含2条记录的发票。

SELECT SalesLed.Invoice, SalesLed.Spiff, Dispatch.Dispatch
  FROM   Dispatch
 INNER JOIN SalesLed
    ON Dispatch.Invoice = SalesLed.Invoice
 WHERE dispatch.Dispatch = 50007

enter image description here

期望的结果:我希望它不返回任何发票,因为其中一个结果的spiff大于0.我想知道是否有一个简单的函数我不知道这个会这样做吗?

5 个答案:

答案 0 :(得分:0)

SELECT SalesLed.Invoice, max(SalesLed.Spiff), Dispatch.Dispatch

FROM Dispatch INNER JOIN SalesLed ON Dispatch.Invoice = SalesLed.Invoice

WHERE dispatch.Dispatch = 50007 group by SalesLed.Invoice,Dispatch.Dispatch

having max(SalesLed.Spiff)<=0

答案 1 :(得分:0)

with x as (select invoice from SalesLed where spiff = 0 
           except
           select invoice from SalesLed where spiff > 0)
SELECT S.Invoice, S.Spiff, D.Dispatch
FROM Dispatch d 
INNER JOIN SalesLed s on D.Invoice = S.Invoice
INNER JOIN x on x.invoice = s.invoice

您可以使用cte首先从salesled表中选择所有发票,其中发票的所有spiff都是= 0.然后在原始查询中使用它来获得所需的结果。

答案 2 :(得分:0)

您也可以按如下方式使用交叉申请;

select
      i.[invoice] as [Invoice]
    , s.[mspiff] as [Spiff]
    , i.[dispatch] as [Dispatch]
from [invoice] i
cross apply
    ( select isnull(max(spiff),0) as [mspiff] from [salesled] where [Invoice] = i.[Invoice]) s
where s.[mspiff] = 0

通过多个答案,您可以看到哪种解决方案最适合您的解决方案。

答案 3 :(得分:0)

一个简单的NOT EXISTS子句可以解决这个问题:

select d.*
  from Dispatch d
 where d.Invoice = 50007
   and not exists (select *
                    from SalesLed s
                   where s.Invoice = d.Invoice
                     and s.spiff > 0)

我的查询假设您实际上并不想显示SalesLed.Spiff的值,因为如果我正确理解您的数据,它总会返回0

答案 4 :(得分:-1)

尝试:

SELECT SalesLed.Invoice, SalesLed.Spiff, Dispatch.Dispatch
FROM Dispatch INNER JOIN SalesLed ON Dispatch.Invoice = SalesLed.Invoice
WHERE dispatch.Dispatch = 50007 AND SalesLed.Spiff > 0