如何在SQL WHERE子句中应用条件语句 [英] How to apply conditional statement in SQL WHERE clause

查看:144
本文介绍了如何在SQL WHERE子句中应用条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我在SQL查询的where子句中应用条件'if'时遇到问题。

这是查询。我删除了WHERE子句中不必要的连接,列名和多个条件,使其可读。

Hi All
I am facing a issue in applying a conditional 'if' in the where clause of the SQL query.
Here is the query. I have removed the unnecessary joins, columns names and multiple conditions in WHERE clause to make it readable.

SELECT TransactionId, TransactionDate , ProcessingDate FROM TransactionDetails
WHERE TransactionId in (2,3,9) AND ...AND ..



现在,我需要从TransactionDetails表中选择另一个事务ID 14和14的记录。 15仅当TransactionDate<>处理该特定记录的日期。



我尝试了什么:



尝试使用IF ELSE - 但它有效只有变量。我想在表格的日期列中应用条件。




Now, I need to select the records from the TransactionDetails table with another transaction Ids 14 & 15 ONLY if the TransactionDate <> ProcessingDate for that particualr record.

What I tried:

Tried using IF ELSE - but it worked only with the variables. I want to apply the condition on the Dates columns from the table.

select  * from transactionDetails
WHERE OrderID in (400376, 400379)
AND
    IF TransactionDate <> ProcessingDate
        TransactionId in (2,3,9,14,15)
    ELSE
        TransactionId in (2,3,9)





我得到两个错误 -

关键字'IF'附近的语法不正确。

'TransactionId'附近的语法不正确。



如果你想让我改进我的问题,请发表评论



I get two errors as -
Incorrect syntax near the keyword 'IF'.
Incorrect syntax near 'TransactionId'.

Please comment if you want me to improve my question

推荐答案

试试:

Try:
select  * from transactionDetails
WHERE OrderID in (400376, 400379)
AND
    ((TransactionDate <> ProcessingDate AND TransactionId in (2,3,9,14,15)
    OR
     (TransactionDate = ProcessingDate AND TransactionId in (2,3,9)))


这篇关于如何在SQL WHERE子句中应用条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆