Search code examples
selectstoreformulassmstemporary-objects

Can I temporarily store a value in the Select Statement of SQL?


In my select statement, I have two returns that are calculations. It looks like this:

 SELECT
     a.FormRate AS 'F-Rate'
     ,a.LoI AS 'Liability'
     ,CAST((A.FormRate * a.LoI / 100) AS DECIMAL(38,2)) 'F-Premium'
     ,a.EndorsementRate AS 'E-Rate'
     ,CAST((A.EndorsementRate * a.LoI / 100) AS DECIMAL(38,2)) 'E-Premium' 

FROM tblAspecs a

Once I have those five statements in the select, I'd like to be able to total E-Premium + F-Premium into a new column. I could always do it this way:

  ,CAST(((A.EndorsementRate * a.Loi / 100) + (a.FormRate * a.LoI / 100)) AS DECIMAL(38,2)) 'Total Premium'

...but that just just seems to be quite sloppy and bulky. Is there a way to store the individual premiums so that I can just do a simple CAST((F-Premium + E-Premium) AS DECIMAL(38,2)) 'Total Premium'

The bulky way also doesn't leave F-Premium and E-Premium dynamic so that if I ever change how they're calculated, I'd have to also change the calculation in the Total Premium column.

Using Microsoft SQL Server Management Studio 2010


Solution

  • Research Common Table Expressions.

    It will look something like this:

    ;WITH [Data]
    (
        [FormRate],
        [Liability],
        [FormPremium],
        [EndorsementRate],
        [EndorsementPremium]
    )
    AS
    (
        SELECT
             a.[FormRate],
             a.[LoI] AS [Liability],
             CAST((a.[FormRate] * a.[LoI] / 100) AS DECIMAL(38,2)),
             a.[EndorsementRate],
             CAST((a.[EndorsementRate] * a.[LoI] / 100) AS DECIMAL(38,2)) 
        FROM 
            tblAspecs a
    )
    SELECT
        [Data].*,
        CAST(([Data].[FormPremium] + [Data].[EndorsementPremium]) AS DECIMAL(38,2)) 'Total Premium'
    FROM
        [Data]