【发布时间】: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