0

今天是个好日子

当我为我的项目创建查询时,我偶然发现了这个错误

当我使用此代码时

DECLARE @MONTH VARCHAR(10)
SET @MONTH = 'MAY'
DECLARE @YEAR VARCHAR(4)
SET @YEAR= '2012'

    SELECT COUNT (*) AS CYJEWELRY
    FROM Transactions.tbl_PawnItem PIT
    INNER JOIN Transactions.tbl_PawnMain PMN
    ON PIT.fld_PawnMainID= PMN.fld_PawnMainID
    INNER JOIN Transactions.tbl_PawnHisto PHI
    ON PHI.fld_PawnMainID = PMN.fld_PawnMainID
    WHERE PMN.fld_StatusID = 3 /* OR PMN.fld_StatusID = 4*/ 
    AND DATEADD(month,DATEDIFF(month,0,PHI.fld_LoanDate),0) =  DATEADD(month,DATEDIFF(month,0,DATEADD (MONTH,-4,@MONTH+@YEAR)),0)
    AND PMN.fld_StorageGroupID  >= 3 and PMN.fld_StorageGroupID <= 14

结果是 CYJEWELRY = 23

当我像这样使用状态 ID 4

DECLARE @MONTH VARCHAR(10)
SET @MONTH = 'MAY'
DECLARE @YEAR VARCHAR(4)
SET @YEAR= '2012'

    SELECT COUNT (*) AS CYJEWELRY
    FROM Transactions.tbl_PawnItem PIT
    INNER JOIN Transactions.tbl_PawnMain PMN
    ON PIT.fld_PawnMainID= PMN.fld_PawnMainID
    INNER JOIN Transactions.tbl_PawnHisto PHI
    ON PHI.fld_PawnMainID = PMN.fld_PawnMainID
    WHERE /*PMN.fld_StatusID = 3  OR */ PMN.fld_StatusID = 4
    AND DATEADD(month,DATEDIFF(month,0,PHI.fld_LoanDate),0) =  DATEADD(month,DATEDIFF(month,0,DATEADD (MONTH,-4,@MONTH+@YEAR)),0)
    AND PMN.fld_StorageGroupID  >= 3 and PMN.fld_StorageGroupID <= 14

结果是 CYJEWELRY = 34

问题是为什么当我像这样使用它们时

DECLARE @MONTH VARCHAR(10)
SET @MONTH = 'MAY'
DECLARE @YEAR VARCHAR(4)
SET @YEAR= '2012'

    SELECT COUNT (*) AS CYJEWELRY
    FROM Transactions.tbl_PawnItem PIT
    INNER JOIN Transactions.tbl_PawnMain PMN
    ON PIT.fld_PawnMainID= PMN.fld_PawnMainID
    INNER JOIN Transactions.tbl_PawnHisto PHI
    ON PHI.fld_PawnMainID = PMN.fld_PawnMainID
    WHERE PMN.fld_StatusID = 3  OR  PMN.fld_StatusID = 4
    AND DATEADD(month,DATEDIFF(month,0,PHI.fld_LoanDate),0) =  DATEADD(month,DATEDIFF(month,0,DATEADD (MONTH,-4,@MONTH+@YEAR)),0)
    AND PMN.fld_StorageGroupID  >= 3 and PMN.fld_StorageGroupID <= 14

结果变成 CYJEWELRY = 380?(我知道这是错误的)而不是 57?

有小费吗?或建议?改进我的代码并删除错误?我会非常感谢我是 t-sql 的新手,请温柔:) 非常感谢:)

4

1 回答 1

1

你需要在 OR 周围添加括号

就像是

WHERE (PMN.fld_StatusID = 3  OR  PMN.fld_StatusID = 4)
AND DATEADD(month,DATEDIFF(month,0,PHI.fld_LoanDate),0) =  DATEADD(month,DATEDIFF(month,0,DATEADD (MONTH,-4,@MONTH+@YEAR)),0)
AND PMN.fld_StorageGroupID  >= 3 and PMN.fld_StorageGroupID <= 14

当您查看执行优先级时

写作

WHEN a = b 
OR   c = d
AND  e = f

这和说的一样

WHEN a = b 
OR   (c = d AND  e = f)

而你的意图在哪里

WHEN (a = b OR c = d)
AND  e = f

看看逻辑运算符优先级

当一个语句中使用多个逻辑运算符时,首先计算 NOT,然后是 AND,最后是 OR。算术和按位运算符在逻辑运算符之前处理。

另请查看运算符优先级 (Transact-SQL)中的表

于 2013-09-10T08:41:45.680 回答