Copy prior month value and insert into new row

谁说胖子不能爱 提交于 2019-12-11 03:56:50

问题


Here is an example of the current table I have:

1) Table name: TotalSales

Name    Year  Month  Sales
------  ----  -----  -----
Alfred  2011  1      100

What I want to do is create a table like this, add a new row(Prior month sales):

2) Table name: TotalSales

Name    Year  Month  Sales  Prior month sales
------  ----  -----  -----  -----------------
Alfred  2011  2      110    100

Not sure how to this, but this is what I have been working on:

SELECT Name, Year, Month, Sales, Sales as [Prior Month sales]
FROM TotalSales
WHERE
DATEPART(month, [Prior Month sales]) = DATEPART(month, DATEADD(month, -1, getdate()))

Thanks for any help


回答1:


To select the given data you need to join the table to itself:

SELECT
    TS.name,
    TS.year,
    TS.month,
    TS.sales,
    COALESCE(TS2.sales, 0) AS prior_month_sales
FROM
    TotalSales TS
LEFT OUTER JOIN TotalSales TS2 ON
    TS2.name = TS.name AND
    (
        (TS2.year = TS.year AND TS2.month = TS.month - 1) OR
        (TS.month = 1 AND TS2.month = 12 AND TS2.year = TS.year - 1)
    )

The LEFT OUTER JOIN is an outer join in case they didn't have any sales the previous month (or this is their first month with the company).




回答2:


I believe this should work...you need to join to itself on name/prior month, but you have 2 test cases for prior month since year/month are stored separately.

select c.Name, c.Year, c.Month, c.Sales, p.Sales
from TotalSales c
left join TotalSales p
on c.Name = p.Name and (
    (c.Month > 1 and c.Year = p.Year and c.Month = p.Month + 1)
    or (c.Month = 1 and c.Year = p.Year + 1 and p.Month = 12))



回答3:


Try something like this to just update the table with the values you want...

UPDATE TotalSales
SET PriorMonthSales = 
(
    SELECT TS.Sales
    FROM TotalSales TS
    WHERE 
    (TotalSales.Month = TS.Month + 1 AND TotalSales.Year = TS.Year)
    OR 
    (TotalSales.Month = 1 AND TS.Month = 12 AND TS.Year = TotalSales.Year -1)
)


来源:https://stackoverflow.com/questions/6873976/copy-prior-month-value-and-insert-into-new-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!