MySQL条件在Date列上

时间:2014-04-30 17:53:02

标签: mysql

有一个包含3个日期字段和ID的表,但定义如下

invoice_date  varchar(255) ---- 2012-04-06 00:00:00 (data stored as)
end_date varchar(255) ----2012-06-30 00:00:00
transaction_date int(11) --- 20120630

并且对于invoice_date和velocity_date,少数记录使用''(空字符串)而不是'NULL'

我的要求是获取20120101和20140331之间的记录

1. if Invoice_date <> '' then use invoice_date
2. If (Invoice_date = ''  and end_date <> '') then use end_date 
3. if (Invoice_date = ''  and velocity_date = '') then use transaction_date

SELECT DISTINCT 
ID,
invoice_date ,
end_date, 
transaction_date
FROM
  temp
WHERE 
CASE
WHEN invoice_date <> '' 
     THEN DATE_FORMAT(CAST(`invoice_date` AS DATE),'%Y%m%d') 
      BETWEEN        20120101 AND 20140331 
WHEN invoice_date = '' AND end_date > '' 
     THEN DATE_FORMAT(CAST(end_date AS DATE),'%Y%m%d') 
      BETWEEN CAST('20120101' AS DATE) AND CAST('20140331' AS DATE) 
WHEN (
      invoice_date = '' 
      AND end_date = ''
    ) 
    OR (
      end_date IS NULL 
      AND invoice_date = ''
    ) 
    OR (
      end_date = '' 
      AND invoice_date IS NULL
       ) 
    THEN DATE_FORMAT(CAST(`transaction_date` AS DATE),'%Y%m%d') BETWEEN 20120101 
    AND 20140331 
  END;

选择并插入之后,在下一步中我必须根据上述日期列进行更新,所以我必须在一个语句中使用这三列来进行内部连接,如

Update table_A Inner Join temp
on (CASE
WHEN invoice_date <> '' 
     THEN DATE_FORMAT(CAST(`invoice_date` AS DATE),'%Y%m%d') 
      BETWEEN        20120101 AND 20140331 
WHEN invoice_date = '' AND end_date > '' 
     THEN DATE_FORMAT(CAST(end_date AS DATE),'%Y%m%d') 
      BETWEEN CAST('20120101' AS DATE) AND CAST('20140331' AS DATE) 
WHEN (
      invoice_date = '' 
      AND end_date = ''
    ) 
    OR (
      end_date IS NULL 
      AND invoice_date = ''
    ) 
    OR (
      end_date = '' 
      AND invoice_date IS NULL
       ) 
    THEN DATE_FORMAT(CAST(`transaction_date` AS DATE),'%Y%m%d') BETWEEN 20120101 
    AND 20140331 
  END = date_id)
  set .........

是吗?因为上面的case语句返回为'1'(不是日期字段)

让我知道,我缺少的任何内容或任何新的方法

谢谢大家!!!

0 个答案:

没有答案