WHERE子句中的条件(Oracle)

时间:2015-05-18 08:38:53

标签: sql oracle subquery

我需要一个根据月份/年份返回数据的查询。下面是我写的子查询返回一行 - start_date和end_date是我需要在主查询中使用的值

WITH SUBQ AS (SELECT 
    dim.MONTH_NAME as current_month_name
   ,dim.year_period as current_month
   ,dim.PERIOD_YEAR as YEAR
   ,CASE WHEN dim.year_period NOT LIKE '%01' THEN to_number(CONCAT(to_char(dim.PERIOD_YEAR-1) , '01' ))
         WHEN dim.year_period LIKE '%01'THEN to_number(CONCAT(to_char(dim.PERIOD_YEAR-2) , '01' ))
         END AS START_DATE 
   ,CASE WHEN dim.year_period NOT LIKE '%01' THEN to_number(CONCAT(to_char(dim.PERIOD_YEAR) , '01'  ))
         WHEN dim.year_period LIKE '%01'THEN to_number(CONCAT(to_char(dim.PERIOD_YEAR-1) , '01'   )) END AS ENDDATE 
  from dim_periods dim    WHERE dim.year_period=to_number(to_char(sysdate, 'YYYYMM')))

问题是 - 我如何使用子查询中的值在where子句中使用一行? 我需要得到这样的东西,我只是不明白我应该如何加入我的子查询和我使用的其余表 -

select * from financial_data fd 
where fd.year_period BETWEEN subq.start_date and subq.enddate

1 个答案:

答案 0 :(得分:0)

您可以使用表格加入子查询,即 CTE ,然后使用过滤谓词中的列名称。 WITH子句中子查询的结果类似于临时表

例如,

<div class="element1"></div>
<tbody>
  <tr></tr>
</tbody>

.element1 {
  display: none;
}

因此,WITH SUBQ AS (SELECT dim.MONTH_NAME AS current_month_name , dim.year_period AS current_month , dim.PERIOD_YEAR AS YEAR , CASE WHEN dim.year_period NOT LIKE '%01' THEN to_number(CONCAT(TO_CHAR(dim.PERIOD_YEAR-1) , '01' )) WHEN dim.year_period LIKE '%01' THEN to_number(CONCAT(TO_CHAR(dim.PERIOD_YEAR-2) , '01' )) END AS START_DATE , CASE WHEN dim.year_period NOT LIKE '%01' THEN to_number(CONCAT(TO_CHAR(dim.PERIOD_YEAR) , '01' )) WHEN dim.year_period LIKE '%01' THEN to_number(CONCAT(TO_CHAR(dim.PERIOD_YEAR-1) , '01' )) END AS ENDDATE FROM dim_periods dim WHERE dim.year_period=to_number(TO_CHAR(SYSDATE, 'YYYYMM')) ) SELECT fd.COLUMNS, q.COLUMNS FROM financial_data fd JOIN subq q ON (fd.KEY = q.KEY) -- join key WHERE fd.year_period BETWEEN q.start_date AND q.enddate; 就像一个临时表,它与SUBQ表一起加入。

更新 OP不需要 ANSI加入语法

financial_data