sql - 复制上个月的值并插入到新行中

标签 sql copy reporting datepart

这是我当前表格的示例:

1) 表名称:TotalSales

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

我想要做的是创建一个像这样的表,添加一个新行(上个月的销售额):

2)表名称:TotalSales

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

不知道如何做到这一点,但这就是我一直在努力的事情:

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

感谢您的帮助

最佳答案

我相信这应该可行...您需要在名称/上个月加入自身,但由于年/月是单独存储的,所以您有上个月的 2 个测试用例。

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))

关于sql - 复制上个月的值并插入到新行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6873976/

相关文章:

php - 在 Joomla 查询中使用 inner join sql 命令时遇到问题

ios - 使标签可复制

MySQL:使用聚合结果进一步计算

c# - 如何动态创建 SSRS 报告?

c++ - 我在哪里可以获得适用于 Qt 5.1.0 或 Qt 5.1.1 的兼容 NCreport 库

php - 如果不存在具有相同值的行,则插入该行

mysql - 在 MySQL 中创建临时列

mysql - MySQL 5.6 中生成列的替代方案是什么

Python shutil.copytree() 在那里跟踪复制的状态

ios - Objective C 中的可变副本有什么作用