如何插入中间行?

时间:2012-01-16 11:19:53

标签: sql tsql

我有下表:

Year    Line    January Febraury   March .... December
2011     B1       5       10         20
2012     B1      10       15         25         ...
2011     A1       4        8         10         ...

我希望每两行插入一个小计行(如果存在),特别是每次yearLine更改时:

Year    Line    January Febraury   March .... December
2011     B1        5       10         20
2012     B1       10       15         25         ...
 ---     B1     +100%   +50%       +25%      ..
2011     A1      4        8          10         ...

如何在T-SQL中执行此操作?

也许使用光标?

1 个答案:

答案 0 :(得分:2)

某些是否要插入新行?或者只能在查询数据时计算小计?

查询版本

SELECT
  Year,
  Line,
  SUM(January)      AS January,
  SUM(February)     AS February,
  ...
  SUM(December)     AS December
FROM
  yourTable
GROUP BY
  Year,
  Line
WITH
  ROLLUP
ORDER BY
  Year,
  Line

插入版本

如果您只是一个级别的摘要,请删除WITH ROLLUP

INSERT INTO
  yourTable
SELECT
  Year,
  NULL,
  SUM(January)      AS January,
  SUM(February)     AS February,
  ...
  SUM(December)     AS December
FROM
  yourTable
GROUP BY
  Year
WITH
  ROLLUP


编辑关注问题编辑

我强烈建议您表示查询,而不是对实际数据的更改。我还建议您在报告环境中构建这些行,或者将%值放在每个记录的右侧......

SELECT
  this_year.Year,
  this_year.Line,
  this_year.January,
  CAST(this_year.January AS DECIMAL(8,2)) / CAST(last_year.January AS DECIMAL(8,2)) AS January_Change,
  ...
FROM
  yourTable   AS this_year
LEFT JOIN
  yourTable   AS last_year
    ON  last_year.year = this_year.year-1
    AND last_year.line = this_year.line