MySQL查询从相似视图汇总到一个结果视图

时间:2018-08-07 20:35:49

标签: php mysql sql

我正在研究一个遇到此问题的项目。场景是我有30个视图,指示每个财政年度的状态计数。所以我的要求是要有一个包含全部30个视图的合计结果视图。希望我的问题很清楚,谢谢。

例如 视图1:

enter image description here

查看2:

enter image description here

结果:

enter image description here

1 个答案:

答案 0 :(得分:0)

首先,您需要将所有30个视图UNION ALL合并为一个“表表达式”,然后按财务年度从中进行选择,如:

select financial_year,
    sum(status_1) as status_1,
    sum(status_0) as status_0,
    sum(status_2) as status_2,
    sum(status_3) as status_3,
    sum(status_4) as status_4
  from (
  select financial_year, status_1, status_0, status_2, status_3, status_4,
      totals from view1
  union all
  select financial_year, status_1, status_0, status_2, status_3, status_4,
      totals from view2
  union all
  select financial_year, status_1, status_0, status_2, status_3, status_4,
      totals from view3
  union all
  ... -- add view4 to view30 here
  ) x
  group by financial_year;