SQL - 在同一行中切换两个不同的日期

时间:2012-06-27 21:58:38

标签: mysql sql

我有一个相当简单的查询:

SELECT invoice_id WHERE employee_id = 'XXXX' AND customer_id = 'YYYY'
    AND [date] < '2012-06-27';

我想知道是否有办法根据条件切换列[日期],在这种情况下是较小或最早的。

换句话说,就像

SELECT invoice_id WHERE employee_id = 'XXXX' AND customer_id = 'YYYY'
    AND (IF(time_created <= transaction_date)) time_created < '2012-06-27' ELSE 
        transaction_date > '2012-06-27');

所以通过比较两列来使用行中最早的日期的查询(尽管看起来time_created似乎总是最早的,但这不是这种情况)。如果没有,我可以将查询分成两部分,但我想知道是否可以在一部分中完成。

2 个答案:

答案 0 :(得分:3)

SELECT invoice_id WHERE employee_id = 'XXXX' AND customer_id = 'YYYY'
AND IF(time_created <= transaction_date, time_created < '2012-06-27', transaction_date > '2012-06-27');

或ANSI SQL解决方案:

SELECT invoice_id WHERE employee_id = 'XXXX' AND customer_id = 'YYYY'
AND CASE WHEN time_created <= transaction_date
         THEN time_created < '2012-06-27'
         ELSE transaction_date > '2012-06-27'
    END

答案 1 :(得分:3)

您可以使用双重条件,例如:

and  (
    time_created <= transaction_date and time_created < '2012-06-27' or
    time_created > transaction_date and transaction_date > '2012-06-27'
)