0

我需要WHERE根据 select 语句中的结果传递两个不同的语句。我的基本查询如下

SELECT table1.taskID, 
    table1.startTime, 
    table1.endTime, 
    table1.everyMinutes, 
    table3.dlid, 
    table3.run 
FROM table1
JOIN table2
    ON table1.taskID = table2.taskID
LEFT JOIN table3
    ON table1.taskID = table3.taskID
WHERE table2.active = '1'
ORDER BY taskID ASC

我正在努力解决的是 if table3.run = '1',那么我需要包括以下内容

CONVERT(DATE,GETDATE()) IN (SELECT dldate FROM table4 WHERE dlid = table3.dlid)

如果table3.run = '0'我需要以下

CONVERT(DATE,GETDATE()) NOT IN (SELECT dldate FROM table4 WHERE dlid = table3.dlid)

最后,如果 table3.run = 'NULL' 那么我不需要这些语句

4

2 回答 2

1

尝试

SELECT table1.taskID, 
    table1.startTime, 
    table1.endTime, 
    table1.everyMinutes, 
    table3.dlid, 
    table3.run 
FROM table1
JOIN table2
     ON table1.taskID = table2.taskID
LEFT JOIN table3
    ON table1.taskID = table3.taskID
WHERE table2.active = '1'
    AND (
            (table3.run = '1' 
             and CONVERT(DATE,GETDATE()) 
             IN (SELECT dldate FROM table4 WHERE dlid = table3.dlid)) 

         or (table3.run = '0' 
             and CONVERT(DATE,GETDATE()) NOT IN 
            (SELECT dldate FROM table4 WHERE dlid = table3.dlid))

         or table3.run = 'NULL'   -- incredibly bad idea
         )
ORDER BY taskID ASC
于 2013-04-18T18:58:41.973 回答
0
SELECT table1.taskID, 
    table1.startTime, 
    table1.endTime, 
    table1.everyMinutes, 
    table3.dlid, 
    table3.run 
FROM table1
JOIN table2
     ON table1.taskID = table2.taskID
LEFT JOIN table3
    ON table1.taskID = table3.taskID
WHERE table2.active = '1' AND ( table3.run = 'NULL' or
  case when CONVERT(DATE,GETDATE()) IN (SELECT dldate FROM table4 WHERE dlid = table3.dlid) then '1'
    else '0'
    end = table3.run )
ORDER BY taskID ASC
于 2013-04-18T19:57:20.487 回答