在带有子查询的SQL查询中,WHERE子句不起作用

时间:2012-11-09 11:49:49

标签: sql sql-server tsql sql-server-2008-r2

我有3个表 - DimWarehousesDimProductsDimTime。我在SQL Query中创建了一个集合。一切都会好的,但我需要的结果是成本或股票不等于0.在我的查询中WHERE条款不起作用。

如何写出哪些条款可行?

where bb.COST <>0 or bb.stock <> 0

查询:

    select 
    bb.TimeKey,
    bb.ProductKey,
    bb.WarehouseKey,
    bb.stock,
    bb.COST
    from(
    SELECT dt.timekey, 
           a.productkey, 
           b.warehousekey,
           Isnull((SELECT SUM(quantyti) 
                   FROM   aa f 
                   WHERE  a.productkey = f.productkey
                          AND b.warehousekey = f.warehousekey 
                          AND f.timekey <= dt.timekey), 0) AS stock, 
           Isnull((SELECT SUM(COST) 
                   FROM   aa f 
                   WHERE  a.productkey = f.productkey 
                          AND b.warehousekey = f.warehousekey 
                          AND f.timekey <= dt.timekey), 0) AS COST
FROM   dimproducts a, 
       (SELECT warehousekey FROM   dimwarehouses) b, 
       (SELECT 20121002 AS timekey ) dt         
     )bb
                where 
bb.COST <>0 or 
bb.stock <> 0

表aa:

TimeKey ProductKey   WarehouseKey   Quantyti    Cost
20120901    1              1          10.000    100.00
20120901    1              1         -10.000    -100.00
20120901    2              1           5.000    50.00
20120901    2              1          15.000    150.00
20120901    2              2           3.000    30.00
20120901    3              1           0.000    20.00
20120901    3              2          10.000    0.00

结果:

TimeKey ProductKey  WarehouseKey    stock   COST
20121002    2                  1    20.000  200.00
20121002    3                  1    0.000   20.00
20121002    2                  2    3.000   30.00
20121002    3                  2    10.000  0.00

我需要结果:

TimeKey ProductKey  WarehouseKey    stock   COST
20121002    2                  1    20.000  200.00
20121002    2                  2    3.000   30.00

2 个答案:

答案 0 :(得分:1)

最后你应该说

where 
bb.COST <>0 and bb.stock <> 0

而不是

where 
    bb.COST <>0 or bb.stock <> 0

如果你想要那个结果。

答案 1 :(得分:0)

要获得您想要的结果,请使用

where bb.COST <>0 AND bb.stock <> 0

使用OR时,如果两个值都不等于0,则返回值不等于0的行。