存储过程使用if else条件插入值

时间:2016-10-14 05:52:24

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

我写了一个工作正常的存储过程。我想计算fd.benefitscontributions的平均值,我可以AVG(fd.benefitscontributions)计算。

如果结果大于50,那么插入好的'别的'坏'在if_funddetails表的status列中。 if_funddetails目前有4列我在三列中插入值但第四列,即status值基于fd.benefitscontributions的平均值

 INSERT INTO if_funddetails  ( d.fundcode,   d.fundname, fd.benefitscontributions )
  SELECT DISTINCT  d.fundcode, d.fundname, fd.benefitscontributions
  FROM   dbo.ws_funddetail AS d 
         LEFT OUTER JOIN dbo.v_fundnooutofpocket AS nop 
                      ON d.funddetailid = nop.funddetailid 
         INNER JOIN dbo.ws_funddata AS fd 
                 ON nop.fundreportid = fd.fundreportid 

我可以获得平均值但是如何增加价值' good'或者“坏”'在状态列中不确定。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

尝试使用AVG功能的Case语句,因为您已经获得了AVG

CASE WHEN AVG(FieldName)>50 THEN 'Good' ELSE 'Bad' END AS 'Status'

注意:要使用聚合功能,您必须将其他列分组

答案 1 :(得分:0)

试试这个..用来了解状态的案例

    INSERT INTO IF_FUNDDETAILS  ( D.FUNDCODE,   D.FUNDNAME,  STATUS )
    SELECT DISTINCT  D.FUNDCODE, D.FUNDNAME, CASE WHEN  AVG( FD.BENEFITSCONTRIBUTIONS)>50 THEN 'GOOD' ELSE 'BAD' END AS STATUS
    FROM   DBO.WS_FUNDDETAIL AS D 
    LEFT OUTER JOIN DBO.V_FUNDNOOUTOFPOCKET AS NOP ON D.FUNDDETAILID = NOP.FUNDDETAILID 
    INNER JOIN DBO.WS_FUNDDATA AS FD ON NOP.FUNDREPORTID = FD.FUNDREPORTID 
    GROUP BY  D.FUNDCODE, D.FUNDNAME

答案 2 :(得分:0)

使用

IIF(AVG(FD.BENEFITSCONTRIBUTIONS)>50 ,'Good', 'Bad') AS 'Status'