如何在SQL查询中忽略0(零)值?

问题描述 投票:-1回答:1

例如:

 food fee   admission fee 
 ------------------------
   100          0 
     0        100 
    50         50 
     0          0

我希望查询忽略两个费用字段中的0(零)值。因此输出应为

 100     0
   0   100
  50    50 

代码

WITH cteReports AS
(
    SELECT               
        tblStudentFees.AdmissionFee, tblStudentFees.BankFee, 
        tblStudentFees.BookFee, tblStudentFees.ClassName, tblStudentFees.Date, 
        tblStudentFees.DivisionName, tblStudentFees.FoodFee, 
        tblStudentFees.OtherFee, tblStudentFees.OtherFee2, 
        tblStudentFees.StationaryFee, tblStudentFees.StudentFeesId, 
        tblStudentFees.StudentNo, tblStudentFees.Total, tblStudent.Name, 
        users.Username, tblState.StateName, tblStudent.StateId, 
        tblStudent.DistrictId, tblStudent.Name AS Expr1, 
        users.Username AS Expr2, tblStudent.CityName, 
        tblStudentFees.PaymentType, tblStudentFees.AccountNo,
        tblStudent.Study
    FROM 
        tblStudentFees AS tblStudentFees 
    LEFT OUTER JOIN
        tblStudent AS tblStudent ON tblStudent.StudentNo = tblStudentFees.StudentNo 
    LEFT OUTER JOIN
        tblState AS tblState ON tblState.StateId = tblStudent.StateId 
    LEFT OUTER JOIN
        tblUser AS users ON tblStudentFees.InsertBy = users.UserId
    WHERE 
        tblStudentFees.AdmissionFee != 0.00 
        AND tblStudentFees.FoodFee = 0.00 
         OR tblStudentFees.AdmissionFee = 0.00 
        AND tblStudentFees.FoodFee != 0.00 
         OR tblStudentFees.AdmissionFee!= 0.00 
        AND tblStudentFees.FoodFee != 0.00
)
SELECT
    AdmissionFee, FoodFee, BankFee, BookFee, ClassName,
    Date, DivisionName, OtherFee, OtherFee2, 
    StationaryFee, StudentFeesId, StudentNo, Total,
    Name, Username, StateName, StateId, DistrictId,
    Expr1, Expr2, CityName, PaymentType, AccountNo 
FROM 
    cteReports 
WHERE
    CityName LIKE '%' + @SearchTerm + '%' 
    AND Date >= @dtfrom 
    AND Date <= @dtTo 
    AND Study = 'TRUE'
asp.net sql-server stored-procedures c#-4.0 left-join
1个回答
0
投票

使用OR时需要括号。

例如

(tblStudentFees.AdmissionFee != 0.00 
AND tblStudentFees.FoodFee = 0.00) 
 OR (tblStudentFees.AdmissionFee = 0.00 
AND tblStudentFees.FoodFee != 0.00) 
 OR (tblStudentFees.AdmissionFee!= 0.00 
AND tblStudentFees.FoodFee != 0.00)

更简单的写法是:

WHERE NOT (FoodFee = 0 AND AdmissionFee = 0)
© www.soinside.com 2019 - 2024. All rights reserved.