简体   繁体   English

子查询与主查询联接

[英]Subquery joined with main query

I need to do a subquery, but need it's value to be based on the main query. 我需要执行子查询,但是需要基于主查询的值。

Basically, I am trying to get the ID , Date , and Value from a table, which we'll call Orders . 基本上,我试图从表中获取IDDateValue ,我们将其称为Orders However, in case there is no Value present on the specified date in there WHERE clause, then I want to know the date where the value was in (whether prior or post the specified date). 但是,如果WHERE子句中的指定日期没有值,那么我想知道该值所在的日期(指定日期之前还是之后)。

The falling query is wrong, but it might explain my logic: 查询下降是错误的,但它可以解释我的逻辑:

SELECT 
   O.ID
  ,O.Date
  ,CASE
      WHEN O.Value IS NULL
      THEN
         (SELECT MAX(Date) 
          FROM Orders AS O1 
          WHERE O1.ID = O.ID
      ELSE O.Value END
   ) as Value
FROM Orders O
WHERE O.date = '2017-01-01'

I'm looking to get the following, for example: 例如,我正在寻找以下内容:

ID    Value
001   100
002   300
003   12-30-2016

You can use CROSS APPLY/OUTER APPLY , it is enabling you to query two or more correlated queries: 您可以使用CROSS APPLY/OUTER APPLY ,这使您能够查询两个或多个相关查询:

select 
       o.id
     , o.date
     , case when o.value is null then t.dt else o.value end as value
from orders o outer apply ( select o1.id, max(date) dt
                            from orders as o1 
                            where o1.id = o.id 
                            group by o1.id
                          ) t
where o.date = 2017-01-01

You just put the closing parens in the wrong place: 您只是将右括号放在错误的位置:

SELECT 
   O.ID
  ,O.Date
  ,CASE
      WHEN O.Value IS NULL
      THEN
         (SELECT MAX(Date) 
          FROM Orders AS O1 
          WHERE O1.ID = O.ID)
      ELSE O.Value
   END as Value
FROM Orders O
WHERE O.date = '2017-01-01'

or using COALESCE: 或使用COALESCE:

  ,COALESCE(O.Value
           ,( SELECT MAX(Date) 
              FROM Orders AS O1 
              WHERE O1.ID = O.ID
            )
           ) as Value

Of course you still might get an error due to non-matching datatypes, then cast both O.Value and the Scalar Subquery to a VarChar. 当然,由于数据类型不匹配,您仍然可能会出错,然后将O.Value和标O.Value查询都转换为VarChar。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM