仅在存在条件之后返回行

时间:2018-07-27 10:13:30

标签: sql sql-server sql-server-2012

我有一个SQL Server查询

这将返回与客户相关的订单或添加到其OrderID(最终发票)的产品的订单

这使用一个存在条件

Select * from Orders o1
where DepartmentSpecialty = 'LivingRoom'
and Exists (SELECT o2.Department  FROM Orders o2    WHERE o2.Department = 'Kitchen' 
    and o1.ID = o2.ID
    and o1.OrderID = o2.OrderID
)

我只希望带回他们从厨房部订购的订购日期之后的行,这些行与他们的OrderID有关。这是从客厅部订购的。

请让我可以修改SQL的任何想法团队

3 个答案:

答案 0 :(得分:0)

也许有点像这样

Select * from Orders o1

where DepartmentSpecialty = 'LivingRoom'

and o1.orderdate >= (SELECT MIN(o2.orderdate) FROM Orders o2    WHERE o2.Department = 'Kitchen' 

and o1.ID = o2.ID
and o1.OrderID = o2.OrderID) 

答案 1 :(得分:0)

这应该可以解决问题

SELECT o1.*
FROM Orders AS o1
    INNER JOIN Orders AS o2 
        ON o1.OrderId = o2.OrderId
        AND o1.[SomeDateField] > o2.[SomeDateField] -- You will need to specify a date field
WHERE o1.DepartmentSpecialty = 'LivingRoom'  -- Department Your interested in
AND o2.DepartmentSpeciality = 'Kitchen' -- Inital Department

答案 2 :(得分:0)

通过使用窗口函数,您可以在没有join或子查询的情况下执行此操作:

select o.*
from (select o.*,
             min(case when o.Department = 'Kitchen'
                      then date
                 end) over (partition by id, orderid) as kitchen_date
      from orders o
     ) o
where o.DepartmentSpecialty = 'LivingRoom' and
      o.date > o.kitchen_date;

我怀疑您原来的join条件(以及partition by列)过于严格。我希望这些是某种客户ID。