SQL存储过程,从另外两个计算列计算的列

时间:2016-10-24 05:40:54

标签: sql sql-server stored-procedures

我想从column3

插入column1+column2(they are calculated columns).个值
Column3 = Column1*.666+Column2*.3333

Column1Column2是从case语句生成的,它们很好,但它只是Column3基于 Column1Column2。任何人都可以帮助我如何计算Column3

任何帮助将不胜感激。

提前致谢

         INSERT INTO IF_FUNDDETAILS  ( D.FUNDCODE,   D.FUNDNAME,  Column1,Column2, Column3)
            SELECT DISTINCT  D.FUNDCODE, D.FUNDNAME, 
    CASE WHEN  AVG( FD.INDUSTRYCONTRIBUTIONS)>80 THEN '80' ELSE '90' END AS Column1,
    CASE WHEN  AVG( FD.BENEFITSCONTRIBUTIONS)>50 THEN '50' ELSE '90' END AS Column2,
            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

3 个答案:

答案 0 :(得分:0)

你不能只用一个插入语句来做。

你能做的是。

  1. 使用除第3列以外的所有值插入表格。

  2. 将第3行的上一行更新为

    更新表tblName设置Column3 = Column1 * .666 + Column2 * .3333 where where子句

  3. 希望这有帮助。

答案 1 :(得分:0)

您无法在查询的同一级别重用别名。所以,只需重复CASE表达式:

INSERT INTO IF_FUNDDETAILS (D.FUNDCODE, D.FUNDNAME, Column1, Column2, Column3)
SELECT DISTINCT
    D.FUNDCODE,
    D.FUNDNAME, 
    CASE WHEN AVG(FD.INDUSTRYCONTRIBUTIONS) > 80 THEN 80 ELSE 90 END AS Column1,
    CASE WHEN AVG(FD.BENEFITSCONTRIBUTIONS) > 50 THEN 50 ELSE 90 END AS Column2,
    0.666 * (CASE WHEN AVG(FD.INDUSTRYCONTRIBUTIONS) > 80 THEN 80 ELSE 90 END) +
    0.333 * (CASE WHEN AVG(FD.BENEFITSCONTRIBUTIONS) > 50 THEN 50 ELSE 90 END) AS Column3
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

注意:我删除了CASE表达式中数字金额周围的单引号,因为您似乎希望将这些表达式的结果视为数字,而不是文本。

答案 2 :(得分:0)

你可以用CTE来做。

;with cte
AS
(
SELECT DISTINCT  D.FUNDCODE, D.FUNDNAME, 
    CASE WHEN  AVG( FD.INDUSTRYCONTRIBUTIONS)>80 THEN '80' ELSE '90' END AS Column1,
    CASE WHEN  AVG( FD.BENEFITSCONTRIBUTIONS)>50 THEN '50' ELSE '90' END AS Column2,
            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

)

INSERT INTO IF_FUNDDETAILS  ( FUNDCODE,   FUNDNAME,  Column1,Column2, Column3)
SELECT * , Column1*.666+Column2*.3333 AS Column3 from cte