联合结果集中制作报表的时候经常被用到,我们可以使用联合结果集将没有直接关系的数据显示到同一张报表中。使用UNION运算符时,只要被联合的结果集符合联合结果集的原则,那么被连接的两个SQL语句可以是非常复杂的,也可以是非常简单。本小节将展示几个使用的例子,一百年两届联合结果集中实际开发中的应用。
1.员工年龄报表
要求查询员工的最低年龄和最高年龄,临时工和正式员工要分别查询。实现SQL语句如下:
SELECT '正式员工最高年龄', MAX(FAge) FROM T_Employee
UNION
SELECT '正式员工最低年龄', MIN(FAge) FROM T_Employee
UNION
SELECT '临时工最高年龄', MAX(FAge) FROM T_TempEmployee
UNION
SELECT '临时工最低年龄', MIN(FAge) FROM T_TempEmployee
+------------------------------------+-----------+
| the maxium age of formal staffs | max(fage) |
+------------------------------------+-----------+
| the maxium age of formal staffs | 35 |
| the minium age of formal staffs | 23 |
| the maxium age of temporary staffs | 45 |
| the minium age of temporary staffs | 23 |
+------------------------------------+-----------+
2.正式员工工资报表
要求查询美味正式员工的信息,包括工号、工资,并且在最后一行加上所有员工工资额的合计。实现SQL语句如下:
+-------------------+----------+
| fnumber | fsalary |
+-------------------+----------+
| DEV001 | 8300.00 |
| DEV002 | 2300.00 |
| DEV003 | 3333.00 |
| HR001 | 4300.00 |
| HR002 | 3300.00 |
| IT001 | 5500.00 |
| IT002 | 2800.00 |
| SALES001 | 5300.00 |
| SALES002 | 8300.00 |
| summary of salary | 43433.00 |
+-------------------+----------+
3. 打印5以内自然数的平方
要求打印出5以内的自然数及它们的平方数。
实现SQL语句如下。
MySQL、MS SQL Server:
SELECT 1, 1*1
UNION
SELECT 2, 2*2
UNION
SELECT 3, 3*3
UNION
SELECT 4, 4*4
UNION
SELECT 5, 5*5
Oracle:
SELECT 1, 1*1 FROM DUAL
UNION
SELECT 2, 2*2 FROM DUAL
UNION
SELECT 3, 3*3 FROM DUAL
UNION
SELECT 4, 4*4 FROM DUAL
UNION
SELECT 5, 5*5 FROM DUAL
+---+-----+
| 1 | 1*1 |
+---+-----+
| 1 | 1 |
| 2 | 4 |
| 3 | 9 |
| 4 | 16 |
| 5 | 25 |
+---+-----+
4.列出员工姓名
要求列出公司所有员工(包括临时工)的姓名,将重复的姓名过滤掉。实现SQL语句如下:
SELECT FName FROM T_Employee
UNION
SELECT FName FROM T_TempEmployee
+---------+
| FNAME |
+---------+
| Tom |
| Jerry |
| Potter |
| Jane |
| Tina |
| Smith |
| NULL |
| Timmy |
| Stone |
| Sarani |
| Yalaha |
| Konkaya |
| Fotifa |
| James |
+---------+
5.分别列出正式员工和临时工的姓名
要求分别列出正式员工和临时工的姓名,并保留重复的姓名。
实现SQL语句如下:
MySQL、MS SQL Server:
SELECT '-Formal Staff Name-'
UNION ALL
SELECT FName FROM T_Employee
UNION ALL
SELECT '-Temporary-'
UNION ALL
SELECT FName FROM T_TempEmployee
+---------------------+
| -Formal Staff Name- |
+---------------------+
| -Formal Staff Name- |
| Tom |
| Jerry |
| Potter |
| Jane |
| Tina |
| Smith |
| NULL |
| Timmy |
| Stone |
| -Temporary- |
| Sarani |
| Tom |
| Yalaha |
| Tina |
| Konkaya |
| Fotifa |
| James |
+---------------------+
Oracle
SELECT 'Formal Employee Name' FROM DUAL
UNION ALL
SELECT FName FROM T_Employee
UNION ALL
SELECT 'Temporary Employee Name' FROM DUAL
UNION ALL
SELECT FName FROM T_TempEmployee