使用case语句时SQL语句中的结果不正确

时间:2015-10-26 10:25:08

标签: sql sql-server sql-server-2008

我正在比较两天的排名。如果旧日排名>新的等级然后增加,否则减少,但我在两种情况下都减少了

 SELECT 
    USERNAME 
    , SUM(IMPROVED) IMPROVED
    , SUM(DECREASED) DECREASED
     , SUM(NoChange) NoChange
    , SUM(TimeLineCOMPLETED) TimeLineCOMPLETED
      , SUM(TLNotCompleted) TLNotCompleted
FROM 
(SELECT (k.keyword)
    ,p.projectname
    ,pa.username
    ,CASE 

        WHEN a.currentposition > b.currentposition
            THEN 1
        ELSE 0
        END IMPROVED
    ,CASE 
        WHEN a.currentposition < b.currentposition
            THEN 1
        ELSE 0
        END  DECREASED
           ,CASE 
        WHEN a.currentposition = b.currentposition
            THEN 1
        ELSE 0
        END NoChange
    ,CASE 
        WHEN pa.KeywordStatus = 'Stopped'
            THEN 1
        ELSE 0
        END TimeLineCOMPLETED
         ,CASE 
        WHEN pa.KeywordStatus = 'InProgress'
            THEN 1
        ELSE 0
        END TLNotCompleted
    ,a.currentposition AS oldposition
    ,b.currentposition AS newposition
    ,pa.KeywordStatus AS TimeLineStatus
    ,k.targetdate
    ,k.positionExp
FROM seo.tbl_keywordposition a
JOIN seo.tbl_keywordposition b ON a.keywordid = b.keywordid
    AND a.psnupdatedate ='10/5/2015' AND b.psnupdatedate ='10/10/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 = 'october_project' AND a.psnupdatedate ='10/5/2015' AND b.psnupdatedate ='10/10/2015'  and pa.KeywordStatus!='NULL' )INNERQUERY GROUP by USERNAME

示例数据

 SELECT * FROM seo.Tbl_KeywordPosition where KeywordId in ('1514','1515')
 PositionId ProjectId   KeywordId   CurrentPosition PsnUpdateDate       
    31592   129           1514        10             2015-10-05           
    31593   129           1514        11             2015-10-10         
    31594   129           1515        10             2015-10-05          
    31595   129           1515         9             2015-10-10    

当前输出

USERNAME    IMPROVED    DECREASED   NoChange    
Ananth           0          2          0     

所需的输出

USERNAME    IMPROVED    DECREASED   NoChange    
Ananth         1          1            0    

因为keywordid 1514 - 旧等级10和新等级11,所以它应该减少。

keywordid 1515 - 旧等级10和新等级9,所以应该增加

3 个答案:

答案 0 :(得分:1)

问题是CurrentPosition应该是varchar cast(a.currentpostion as int)vs cast(b.currentposition as int)

答案 1 :(得分:0)

基于样本和结果:

list

答案 2 :(得分:0)

您查询的ON子句&#34; pa.KeywordStatus!=&#39; NULL&#39;&#34;会产生不好的结果,可能你可能要把它变成pa.KeywordStatus IS NOT NULL