通过聚合其他列动态创建列

时间:2017-03-21 14:01:41

标签: sql sql-server

我正在尝试通过根据各自的“代码”列对“PremiumByCode”列的值进行求和来创建一个名为“Premium”的新列。我想在最终结果中仅显示非零的Premium行..而且,我试图近似最终的Premium列,没有小数值。我正在使用MS SQL,这是我的下面的代码。

我想创建新列,如下所示:

每个代码

pages,最后只显示非零[Premium]值

的记录
tt_content

我目前的表格如下:

[Premium] = max([PremiumByCodes])

我的预期输出如下:

   ...............
    select  a.FileID,
                a.InsName, 
                a.[Policy Number],
                a.[Effective Date], 
                a.LOB, 
                b.Codes, 
                --a.[NWP],              
                [PremiumByCodes]  = a.[NWP]/(1-c.[Commission%]-c.[Deduction%]),
                c.[Commission%]*100 as Commission,
                c.[Deduction%]*100 as Deduction,  
                c.[Currency]


                --Codes_Commission = [Premium] * c.[Commission%]
        from #temp1 a
        inner join IT.dbo.Perils_Codes_Lookup b 
        on b.Peril = a.LOB

        right join (
        -- Extract Commission Information
            select FileID, 
                    --ISNULL([Commission], 0) as Commisssion,
                    CAST (ISNULL([Commission], 0) as float) as [Commission%],           
                    CAST (ISNULL([Deduction], 0) as float) as [Deduction%],
                    ISNULL([Currency],0) as [Currency]
        from (select FileID, Worksheet, Label,LOB,Data
        from IT.[dbo].[DATA] 
        where 
        FileID = 18265
        and Worksheet in ('Summary')
        and LOB in ( 'N/A')
        ) d 
        PIVOT
            (max([Data]) 
             for [Label] in ([Commission], [Deduction],[Currency])
             --,[Commission])
            )piv 
        )c

        on c.FileID = a.FileID

2 个答案:

答案 0 :(得分:1)

我会创建一个视图,函数或另一个临时表,它只返回一个包含每个代码及其聚合溢价的集合。然后加入该视图,函数或临时表。

通过这种方式,您可以对结果执行任何后续逻辑。并且您可以过滤掉返回零的代码。

答案 1 :(得分:0)

将该字段花费为金钱

 CONVERT(varchar, CAST(Premium AS money), 1)