查询以检查属性是否在LAST YEAR的表中

时间:2017-07-06 18:32:37

标签: sql oracle11g

我试着写一个CASE语句来查看school_name与school_form_status =是否已完成,当前年份是否也已在上一年完成。

   school_name | School_status | Report date|  FORM_PREVIOUS_YEAR
________________________________________________________________________________    

     Paul Keys |    Completed  | 03/31/2016  |      YES

这就是我所拥有的,但不起作用,我是初学者

    select 
    CASE REPORTED_DATE YEAR = REPORTED_DATE, YEAR,-1,DateAdd(Year,DATEDIFF(YEAR,0,getdate()),0))
    THEN 'Y'
     ELSE 'N'
    END AS FORM_PREV_YEAR,
    from 
    TABLE1

2 个答案:

答案 0 :(得分:0)

通常情况下,你会自动加入表格:

SELECT this_year.school_name,
       this_year.school_status,
       this_year.reported_date,
       CASE WHEN last_year.school_status = 'Completed' THEN 'Y' ELSE 'N' END AS form_previous_year
FROM table1 AS this_year
LEFT OUTER JOIN table1 AS last_year ON last_year.school_name = this_year.school_name
WHERE this_year.reported_date >= TO_DATE('2017-01-01', 'YYYY-MM-DD')
  AND last_year.reported_date BETWEEN TO_DATE('2016-01-01', 'YYYY-MM-DD') AND TO_DATE('2016-12-31', 'YYYY-MM-DD')
  AND this_year.school_status = 'Completed'

该声明会查找已完成状态的所有学校以及来自今年广告的reports_date然后查找具有相同名称的学校和去年的reported_date(如果存在)(LEFT OUTER JOIN)。如果去年的状态为“已完成”,则返回“是”否则为“否”。

答案 1 :(得分:0)

试试这段代码:

select 
CASE WHEN school_status = 'Completed' and EXTRACT(year from report_date) = EXTRACT(year from sysdate)-1
THEN 'Y'
ELSE 'N'
END AS FORM_PREV_YEAR 
from table1;