我可以从WHERE子句中排除MSSQL中的单个SELECT吗?

时间:2013-01-28 20:40:48

标签: sql sql-server database

我有一个查询,它提取了我需要通过多个WHERE子句过滤的大量信息。但是,我不希望我的主表(在本例中为inv_data)受所有WHERE子句的影响。有没有办法选择哪些表受哪个WHERE影响?

这是我当前的查询:

$query_ats = "SELECT
                i.prod_cd as product,
                i.descrip as description,
                i.in_stock as current_stock, 
                SUM(p.log_qty) as purchase_order,
                SUM(l.order_qty + e.order_qty) as total_so
            from
                inv_data as i
                inner join plog as p
                    on i.prod_cd = p.prod_cd
                inner join ord_log as l
                    on i.prod_cd = l.prod_cd
                inner join ediordlg as e
                    on i.prod_cd = e.prod_cd
            where
                i.class_cd = 'ALG7'
            AND 
            dateadd(day, p.EST_DT, '18001228') BETWEEN getdate() and dateadd(day, 14, getdate())
            AND 
            dateadd(day, l.SHIP_DT, '18001228') BETWEEN getdate() and dateadd(day, 14, getdate())
            AND 
            dateadd(day, e.SHIP_DT, '18001228') BETWEEN getdate() and dateadd(day, 14, getdate())
            group by
                i.prod_cd,
                i.descrip,
                i.in_stock,
            order by
                i.prod_cd ASC";

表i(inv_data)是我不希望受任何dateadd子句影响的主表。

谢谢!

1 个答案:

答案 0 :(得分:1)

左外连接条件并将条件移动到on子句:

SELECT i.prod_cd as product,
       i.descrip as description,
       i.in_stock as current_stock, 
       SUM(p.log_qty) as purchase_order,
       SUM(l.order_qty + e.order_qty) as total_so
from inv_data i left outer join
     plog p
     on i.prod_cd = p.prod_cd and
        dateadd(day, p.EST_DT, '18001228') BETWEEN getdate() and dateadd(day, 14, getdate())
     left outer join
     ord_log l
     on i.prod_cd = l.prod_cd and
        dateadd(day, l.SHIP_DT, '18001228') BETWEEN getdate() and dateadd(day, 14, getdate()) 
     left outer join
     ediordlg e
     on i.prod_cd = e.prod_cd and
        dateadd(day, e.SHIP_DT, '18001228') BETWEEN getdate() and dateadd(day, 14, getdate())
where i.class_cd = 'ALG7'
group by i.prod_cd, i.descrip, i.in_stock,
order by i.prod_cd ASC