因此,我已经搜索了类似的问题并找到了相似的结果,但是找不到适合我的特定问题的任何内容。我是SQL的新手,所以我不知道我要问的内容是否可能。
我正在尝试将预算数据从两个不同的表插入到一个表中,我需要将结果按每个“组”分开,但是我还想在分组数据的开头显示每个组的总预算。例如:
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个组,每个组的总预算,所以是否有一种方法可以遍历此表的结果并为每个组建立并集?
类似这样,但是我不知道while循环在SQL中如何工作:
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]
每个联合的列和全部相同,唯一的区别是组的名称。
为了方便起见,我强调了我的主要问题。
获得有保证的排序顺序的唯一方法是使用group by
。没有例外。
如果需要维护UNION或UNION ALL中的行顺序,则需要将其包括为可用于对行进行排序的列。典型的方法是:
select *
from (
select 1 as sort_order, [columns] from [table 1] where group = [Hardcoded GROUP 1 Name]
UNION ALL
select 2 as sort_order, [columns] from [table 2] where group = [Hardcoded GROUP 2 Name]
UNION ALL
select 2 as sort_order, [columns] from [table 1] where group = [Hardcoded GROUP 2 Name]
....
) u
order by sort_order;