在使用案例时在sql中得到错误的总和

时间:2015-02-03 06:16:37

标签: sql sql-server

  • 我在sql out put
  • 中获取不正确的数据
  • 它应该会有所改善2,但即使没有成为减少计数的原因,它也总是增加1减少计数
  • 从第一个查询输出计数并从另一个查询计数显示

查询

SELECT USERNAME,
       Sum(IMPROVED)  IMPROVED,
       Sum(DECREASED) DECREASED
FROM   (SELECT ( k.keyword ),
               p.projectname,
               pa.username,
               CASE
                 WHEN a.currentposition > b.currentposition THEN 1
               END               IMPROVED,
               CASE
                 WHEN b.currentposition > a.currentposition THEN 1
               END               DECREASED,
               a.currentposition AS oldposition,
               b.currentposition AS newposition
        FROM   seo.tbl_keywordposition b
               JOIN seo.tbl_keywordposition a
                 ON a.keywordid = b.keywordid
                    AND a.psnupdatedate = '1/22/2015'
                    AND b.psnupdatedate = '1/23/2015'
               LEFT JOIN tbl_keywords k
                      ON k.keywordid = b.keywordid
                         AND a.keywordid = b.keywordid
               LEFT JOIN tbl_project p
                      ON p.ProjectId = k.ProjId
               LEFT JOIN tbl_projAssignment pa
                      ON pa.ProjId = p.ProjectId
                         AND pa.KeywordID = k.keywordid
        WHERE  p.Projectname = 'krishnaproject1')INNERQUERY
GROUP  BY USERNAME 

我错误的屏幕截图。请看这个链接 http://postimg.org/image/d8s6rsgvt/

2 个答案:

答案 0 :(得分:0)

更改你的case语句,将else值设置为0,因为当你没有将它设置为任何东西时,它会将值赋值为NULL,null和数字的总和是什么?注意1来自哪里:唯一具有非null Column1和Column2的行。

           CASE
             WHEN a.currentposition > b.currentposition THEN 1
             ELSE 0
           END IMPROVED,
           CASE
             WHEN b.currentposition > a.currentposition THEN 1
             ELSE 0
           END  DECREASED,

或者您也可以在外部选择中使用COALESCE

         SELECT USERNAME,
               Sum(COALESCE(IMPROVED,0))  IMPROVED,
               Sum(COALESCE(DECREASED,0)) DECREASED

答案 1 :(得分:0)

在您的子查询中对USERNAME进行分组。

WHERE  p.Projectname = 'krishnaproject1' GROUP  BY USERNAME )INNERQUERY