SQL在计算中避免0

时间:2017-10-12 17:01:30

标签: sql sql-server database

任何人都可以帮我解决这个问题吗? “Lost_Weight”是一个计算字段,我试图获得HWeight的结果 - 如果renWeight为0,则renWeight ='0'。where子句有一个有争议的声明,它给我带来了挑战,以实现这一点。见下文。

SELECT        TOP (100) PERCENT dbo.Name.ID,
                        dbo.Name.CO_ID, 
                        dbo.Name.FULL_NAME, 
                        dbo.Name.STATE_PROVINCE, dbo.Tops_Profile.START_WGHT, 
                        dbo.Tops_Profile.RENEWAL_WEIGHT, 
                        dbo.Tops_Profile.H_WEIGHT - dbo.Tops_Profile.RENEWAL_WEIGHT AS Lost_Weight, 
                        dbo.Tops_Profile.H_WEIGHT, 
                        dbo.Name.JOIN_DATE,
                        dbo.Name.BIRTH_DATE, 
                        RIGHT(dbo.TOPS_AWARDS.AWARD_TYPE, 15) AS AWARDS_TYPE, 
                        dbo.TOPS_AWARDS.AWARD_CATEGORY, 
                       dbo.TOPS_AWARDS.AWARD_DATE, 
                       dbo.vw_RegDirs.TARGET_ID AS 
                        RD_ID,
                       dbo.vw_Coords.TARGET_ID AS Coord_ID, 
                       dbo.vw_Coords.FULL_NAME AS 
                      Coord_Name, 
                      dbo.vw_AreaCapts.TARGET_ID AS AC_ID, dbo.Name.STATUS
FROM            dbo.Name INNER JOIN  dbo.Tops_Profile 
   ON dbo.Name.ID = dbo.Tops_Profile.ID 
INNER JOIN  dbo.vw_RegDirs 
                        ON dbo.Name.CO_ID = dbo.vw_RegDirs.CHAPTER
INNER JOIN dbo.vw_Coords 
                    ON dbo.Name.CO_ID = dbo.vw_Coords.CHAPTER 
INNER JOIN  dbo.vw_AreaCapts 
      ON dbo.Name.CO_ID = dbo.vw_AreaCapts.CHAPTER 
LEFT OUTER JOIN  dbo.TOPS_AWARDS 
    ON dbo.Name.ID = dbo.TOPS_AWARDS.ID
WHERE        (dbo.Tops_Profile.RENEWAL_WEIGHT <> '0')
            AND (dbo.Name.STATUS = 'a') 
       AND (dbo.Tops_Profile.H_WEIGHT - dbo.Tops_Profile.RENEWAL_WEIGHT >= 100') 
   OR (dbo.Name.STATUS = 'a') AND (dbo.TOPS_AWARDS.AWARD_TYPE LIKE '%Century%')

现在如果renewal_weight为0,它会自动从Lost_Weight字段中的H_WEIGHT给我一个数字,如果RENEWAL_WEIGHT为0,我需要结果为0.

1 个答案:

答案 0 :(得分:1)

在这种情况下,我猜0是特殊值。这可以通过使用CASE

来解决

替换

dbo.Tops_Profile.H_WEIGHT - dbo.Tops_Profile.RENEWAL_WEIGHT AS Lost_Weight

使用

CASE WHEN  RENEWAL_WEIGHT = 0 THEN 0 
     ELSE dbo.Tops_Profile.H_WEIGHT - dbo.Tops_Profile.RENEWAL_WEIGHT
END  AS Lost_Weight