如何通过操作选择所有订单号,但是根据操作时间限制某些订单?

时间:2016-10-13 19:02:30

标签: sql sql-server sql-server-2012

我有一个存储过程,目前根据工作中心提取所有订单号和操作。

我将它设置为专门省略2个操作(在WHERE语句中)

     AND operation NOT IN ('Test1', 'Test2')

我需要更改它以包含这些操作,但是,只有它们已经存在了不到一段时间。我的确有一个开始日期的专栏,格式为'YYYY-MM-DD HH:MM:SS.0000000'

我正在使用的列的示例是:

    Order    operation    start_date
    AW1234     Test1     2016-10-02 20:18:39.0000000
    WEFDO43    Test2     2016-10-02 04:18:39.0000000
    WEFVO43    OP1     2016-10-02 04:18:39.0000000
    WEXJO43    LITTLE     2016-10-02 04:18:39.0000000
    WEBJO43    BIG    2016-10-02 04:18:39.0000000
    WEWJO43    TIN     2016-10-02 04:18:39.0000000

我尝试将其添加到'WHERE'并创建CASE,但我最后迷路了

    --, (SELECT CASE WHEN w.operation like '%FAR-CMPHLD%' AND Need_Date < getdate() - 6 ....ELSE END...)

如果这些操作的订单编号是在最近X天内启动而不更改原始查询的,那么如何添加这些操作?

我正在使用SQL Server 2012

2 个答案:

答案 0 :(得分:0)

我最终在原始代码中添加了一个UNION,嵌套代码如下所示:

               SELECT *
               FROM
               (*Original code*
                SELECT *
                FROM Testing1 w, Testing2 so
                WHERE w.Site = 'OROR'
                AND so.shop = w.shop
                AND w.operation NOT IN ('Test1', 'Test2') 
                AND convert(Date, actual_start_date, 120) >= GETDATE() - 10

                UNION

                SELECT *
                FROM Testing1 w, Testing2 so
                WHERE w.Site = 'OROR'
                AND so.shop = w.shop
                AND w.operation Like('Test1') 
                AND convert(Date, actual_start_date, 120) >= GETDATE() - 8

                UNION

                SELECT *
                FROM Testing1 w, Testing2 so
                WHERE w.Site = 'OROR'
                AND so.shop = w.shop
                AND w.operation Like('Test2') 
                AND convert(Date, actual_start_date, 120) >= GETDATE() - 4) b
这样做可以让我分别选择这些操作并控制他们在该操作中的时间,因为他们需要不同

会喜欢更简单的版本,但这个版本运行得很好

答案 1 :(得分:0)

您需要的只是OR,例如:

SELECT *
FROM 
   Testing1 w inner join 
   Testing2 so on
   so.shop = w.shop and
   w.Site = 'OROR'
WHERE
   (w.operation = 'Test1' AND 
convert(Date, actual_start_date, 120) >= GETDATE() - 8) OR
   (w.operation = 'Test2' AND 
convert(Date, actual_start_date, 120) >= GETDATE() - 4) OR
   (w.operation NOT IN ('Test1', 'Test2') AND 
convert(Date, actual_start_date, 120) >= GETDATE() - 10 )

甚至:

SELECT *
FROM 
   Testing1 w inner join 
   Testing2 so on
   so.shop = w.shop and
   w.Site = 'OROR'  AND 
   convert(Date, actual_start_date, 120) >= GETDATE() - 10
WHERE
   (w.operation = 'Test1' AND 
convert(Date, actual_start_date, 120) >= GETDATE() - 8) OR
   (w.operation = 'Test2' AND 
convert(Date, actual_start_date, 120) >= GETDATE() - 4) OR
   (w.operation NOT IN ('Test1', 'Test2'))