将去年的价值保存在当前 table

Save value from last year in current table

这是一个关于数据库设计的更普遍的问题。 我目前正在将 Excel/VBA 程序迁移到 SQL 并遇到以下情况,我需要深思熟虑,因为我是第一次这样做。

excel的现状: excel sheet

部分新MySQLtable到目前为止:

+--------------+-------------------+---------+----------+-------+---------------+
| licenseplate | mileage_last_year | january | february | march | first_quarter |
+--------------+-------------------+---------+----------+-------+---------------+
| BP 11-111    |              NULL |     100 |      100 |   100 |           300 |
| BP 11-222    |              NULL |     561 |     1111 |   707 |          2379 |
+--------------+-------------------+---------+----------+-------+---------------+

"first_quarter"等都是生成的列,目前没问题

但是,将当年的里程数保存到下一年的最佳做法是什么?

  1. 每年一个新的 table 并根据用户的选择从前端查询?
  2. 每个 licenseplate/car 和年份一个新行并且只在前端显示当前年份?

首先,您需要确定要存储的数据的粒度: 这里,是年、月级别的里程数。因此,您可以相应地决定 table 结构和粒度。

您需要归一化为不同的 table。

  • 年Table(年)
  • 月份Table(MonthId,MonthName,QuarterName)

  • LicensePlate Table(LicensePlateId,LicensePlateName)

  • 里程Table(LicensePlateId, Year, MonthId, Milage)

您现在可以推导出牌照特定年份和月份的里程数是多少。您可以在需要时在季度级别聚合值。

注意:可以将Year,Month信息组合成一个calendarMonthTable(CalendarId, Year, Month, MonthName, QuarterName),是月级别的粒度还有。

数据库是数据的持久存储。在格式化方面,不要认为数据库具有电子表格的功能;那是为了前端。

"no problem so far" -- 错误.

不要把一堆东西跨栏放置。相反,每个月一行。

通常最好在客户端进行格式化,而不是SQL。但是可以 "pivot" 将月份放在输出中。

应该计算总计和小计,而不是存储。

"new table for every ..." -- 几乎总是糟糕的模式设计。 Whosebug 上的许多 个问题都在问这个问题;答案总是一样的:"no".

"new row for every licenseplate/car and year and only display the current year" -- 这可以在SQL(稍微复杂)或在前端处理。