【问题标题】:INSERT with UNION ALL records from different tables in a loop?在循环中插入来自不同表的 UNION ALL 记录?
【发布时间】:2020-03-03 03:25:14
【问题描述】:

我正在尝试将预算数据插入来自两个不同表的表中,我需要将结果按每个“组”分隔,但我还想在分组的开头显示每个组的总预算数据。

例如:

Group 1               Total Budget
G1 Component          Budget
G1 Component          Budget
G1 Component          Budget
Group 2               Total Budget
G2 Component          Budget
G2 Component          Budget
Group 3, etc..

不幸的是,我不能使用order by,因为结果不是按字母顺序排列的,并且没有保留用户想要的顺序的 ID 序列。我没有设计我从中选择的表格,也没有我可以改变它们吗,所以我必须使用我所得到的。

现在我的代码如下所示,以保持所有内容出现在表格中的顺序

   select [columns] from [table 1] where group = [Hardcoded GROUP 1 Name]
   UNION ALL
   select [columns] from [table 2] where group = [Hardcoded GROUP 1 Name]
   UNION ALL
   select [columns] from [table 1] where group = [Hardcoded GROUP 2 Name]
   UNION ALL
   select [columns] from [table 2] where group = [Hardcoded GROUP 2 Name]
   UNION ALL
   select [columns] from [table 1] where group = [Hardcoded GROUP 3 Name]
   UNION ALL
   select [columns] from [table 2] where group = [Hardcoded GROUP 3 Name]
   UNION ALL
   select [columns] from [table 1] where group = [Hardcoded GROUP 4 Name]
   UNION ALL
   select [columns] from [table 2] where group = [Hardcoded GROUP 4 Name]
   UNION ALL
   select [columns] from [table 1] where group = [Hardcoded GROUP 5 Name]
   UNION ALL
   select [columns] from [table 2] where group = [Hardcoded GROUP 5 Name]

目前共有 5 组。

我担心每个组的值都是硬编码的。 但是这个插入是针对最终用户需要计算的每个预算进行的,我不知道将来组的数量是否会发生变化。

我上面的代码中引用的“表 1”只包含 5 个组,每个组的总预算,所以 有没有办法循环遍历该表中的结果并为每个组创建联合?

类似这样,但我不知道 SQL 中的 while 循环如何工作:

retrieve group names as results
while results not null
   select [columns] from [table 1] where group = [RESULT]
   UNION ALL
   select [columns] from [table 2] where group = [RESULT]

每个联合的列和所有都是相同的,唯一的区别是组的名称。

【问题讨论】:

  • 获得保证排序顺序的唯一方法是使用order by。也不例外。
  • 抱歉,我在完成之前不小心按了 Enter,所以 order by 对我不起作用,因为我不是按名称或列排序。
  • @a_horse_with_no_name 我不完全确定。我正在使用 SSMS 来测试所有内容,但它最终会出现在 PHP 应用程序中,所以我不确定如何回答这个问题。

标签: sql sql-server union


【解决方案1】:

我认为 order by 仍然是要走的路。您将需要执行一些子查询。这样您将获得按组名分组的结果。

SELECT * 
FROM 
(   
   select [columns] from [table 1] 
   UNION ALL
   select [columns] from [table 2] 
)
ORDER BY [group]

至于在这些组之间插入总预算,这将是一个非常丑陋的查询,在显示数据之前在 PHP 脚本中计算它可能更容易。

【讨论】:

  • 是的,我一直在到处寻找最好的整体设计是什么。不知道用SQL控制多少,用PH​​P控制多少,只希望优雅高效。
猜你喜欢
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 2018-08-04
相关资源
最近更新 更多