SQL Server - 使用带有CONVERT的NULLIF来计算多个BIT字段

时间:2014-11-07 09:57:13

标签: sql sql-server

我有这个问题:

SELECT 
    Percentages.ProjectID,
    SUM(Percentages.Percent1) + 
       SUM(Percentages.Percent2) /
       ISNULL(NULLIF(CONVERT(INT, Finances.IncludeP1), 0) + 
       NULLIF(CONVERT(INT, Finances.IncludeP2), 0), 1)
FROM
    Percentages
INNER JOIN 
    Finances ON Percentages.ProjectID = Finances.ProjectID
GROUP BY 
    Percentages.ProjectID

这种方式的工作方式是这样的,当字段(Price1)和(Price2)的值不为零时(可以是正数或负数),则调用位字段( IncludeP1)和(IncludeP2)为TRUE(1)

由于你不能除以零,我需要能够使IncludeP1 OR IncludeP2或两者的值为NULL。然后ISNULL进来,因为我想要显示原始值,所以将此除以1得到所需的结果。

我在上述查询中遇到的错误是由于Finances.IncludeP1Finances.IncludeP2未包含在群组语句中,但是包含它们意味着所需的ProjectID分组确实存在没有工作...有没有办法做到这一点,还是我需要重新考虑这是如何工作的?

感谢您的帮助

enter image description here

2 个答案:

答案 0 :(得分:0)

使用以下查询解决了这个问题:

   SELECT 
    Finances.ProjectID,
    SUM(Finances.Percent1 + Finances.Percent2 + Finances.Percent3)
    /
    ISNULL(
           NULLIF(SUM(CASE WHEN (Finances.IncludeP1 = 1) THEN 1 ELSE 0 END),0) +
           NULLIF(SUM(CASE WHEN (Finances.IncludeP2 = 1) THEN 1 ELSE 0 END),0) +
           NULLIF(SUM(CASE WHEN (Finances.IncludeP3 = 1) THEN 1 ELSE 0 END),0) 
        ,1)Answer,
    from Finances
    group by Finances.ProjectID

答案 1 :(得分:0)

SELECT ProjectID
      ,AVG([Percent])
FROM Finances
     CROSS APPLY (
         VALUES (PercentP1, IncludeP1)
               ,(PercentP2, IncludeP2)
               ,(PercentP3, IncludeP3)
     ) AS T([Percent], Include)
WHERE Include = 1
GROUP BY ProjectID