Derived/calculated column on existing table

后端 未结 3 2011
盖世英雄少女心
盖世英雄少女心 2021-01-25 16:38

I have been going nuts over this issue for some time and I am seeking help.

I have SQL Server table with values, as follows:

Account - Date - Amount - Su         


        
相关标签:
3条回答
  • 2021-01-25 17:12
    SELECT    l.*, 
              q.summary AS SummaryPreviousYear
    FROM      lists l
    LEFT JOIN 
         (
              SELECT    Date, 
                        Summary
              FROM      lists 
              WHERE     MONTH(Date) = 12
         ) AS q  
              ON YEAR(l.Date) = YEAR(q.Date) + 1
    
    0 讨论(0)
  • 2021-01-25 17:21

    Why are you duplicating this summary and previous year summary data for each row in your database? This is wasteful and unnecessary. It would be far better to have another table with previous year summaries, one row per year, that you could join to this table. And, I don't see a need for a Summary column at all. Why not create a view that calculates a Summary, when the month is 12, and returns a zero for any month not equal to 12.

    0 讨论(0)
  • 2021-01-25 17:30
    SELECT 
        t.Account,
        t.Date,
        t.Amount,
        t.Summary,
        s.Summary as SummaryPreviousYear
    FROM TestTable t    
    JOIN (
        SELECT
            Account,
            DATEPART(YEAR, Date) as Year,
            SUM(Amount) as Summary
        FROM TestTable
        GROUP BY Account, DATEPART(YEAR, Date)
    ) s
        ON s.Account = t.Account
        AND s.Year = DATEPART(YEAR, Date) - 1
    
    0 讨论(0)
提交回复
热议问题