在SQL中使用Case进行逐行计算

时间:2014-02-24 07:46:49

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

这是查询:

SELECT CASE Count(RADLD.request_id) 
         WHEN 0 THEN (SELECT Sum(Datediff(dd, rad.clarity_dt, Getdate()))) 
         ELSE (SELECT Sum(Datediff(dd, radld.clarity_dt, Getdate()))) 
       END 
FROM   ppa.request_add_details rad, 
       ppa.request_add_details_loop_details radld, 
       ppa.request req 
WHERE  radld.request_id = rad.request_id 
       AND radld.request_id = req.request_id 
       AND rad.clarity_dt IS NOT NULL 
       AND ( rad.recomm_dt IS NULL ) 
       AND rad.modified_by !=- 1 
       AND rad.request_id = req.request_id 
       AND ( ( radld.loop_sequence = CASE 
                                     WHEN radld.loop_sequence IS NOT NULL THEN 1 
                                     END ) 
              OR ( radld.loop_sequence IS NULL ) ) 

这就是我希望它工作的方式:如果找到request_id,则找到radld thn中的条目,它应该用于

select sum(datediff(dd,radld.clarity_dt,getdate()))

如果在radld中找不到相应的条目,那么它应该用于

select sum(datediff(dd,rad.clarity_dt,getdate())) ..

实际发生的情况是:如果任何请求记录在 radld 中找到,那么它会将select sum(datediff(dd,radld.clarity_dt,getdate()))应用于所有记录。

请帮忙

1 个答案:

答案 0 :(得分:0)

在您的查询中,您已完成内部联接,这意味着它将仅返回所有表中的请求(rad,radld和req)。所以从来没有像Count(RADLD.request_id)那样的情况将为0.所以所有记录都会有相同的结果。您应该使用LEFT or RIGHT JOIN检查它并检查NULL数据而不是COUNT。所以你可以得到你想要的正确结果。

尝试以下内容:

SELECT CASE WHEN radld.request_id IS NOT NULL 
            THEN (SELECT Sum(Datediff(dd, radld.clarity_dt, Getdate()))) 
            ELSE (SELECT Sum(Datediff(dd, rad.clarity_dt, Getdate()))) END 
FROM   ppa.request req 
LEFT JOIN ppa.request_add_details_loop_details radld ON req.request_id = radld.request_id
LEFT JOIN ppa.request_add_details rad ON radld.request_id = rad.request_id
WHERE rad.clarity_dt IS NOT NULL 
AND rad.recomm_dt IS NULL
AND rad.modified_by !=- 1 
AND ((radld.loop_sequence = 1) OR (radld.loop_sequence IS NULL))