sql语句 如何合并查询结果?

2024-12-29 15:21:13
推荐回答(4个)
回答1:

给楼主看个例子:
table T_Test
id uname
----------------
1 张三
2 李四
3 王武
4 赵六
5 孙钱
6 周启
========================
table T_Test2
id age
---------------
1 29
3 19
4 24
5 26
7 28
=========================
select a.id,a.uname,b.age from (select * from T_Test) as a,(select * from T_Test2) as b where a.id=b.id

执行结果如下:
=========================
id uname age
-----------------------
1 张三 29
3 王武 19
4 赵六 24
5 孙钱 26
===========================
这里相当于使用了inner join
楼主只要把两个括号里面的select语句换成你上面的大语句就可以了

select a.站点号 as 站点号,a.台站名称 as 台站名称,a.2000年降水量平均值 as 2000年降水量平均值,b.2001年降水量平均值 as 2001年降水量平均值
from
(
select Tb_station.iiiii as '站点号',Tb_station.tzmc as '台站名称',
avg(Tb_qxcydek.r) as '2000年降水量平均值'
from Tb_qxcydek,Tb_station
where Tb_qxcydek.iiiii = Tb_station.iiiii and (Tb_qxcydek.datedek >= 200001 and Tb_qxcydek.datedek <= 200005)
group by Tb_station.tzmc,Tb_station.iiiii
having Tb_station.iiiii in ('58015','58016','58102','58107','58108','58109')
order by Tb_station.iiiii,Tb_station.tzmc
)
as a
,
(
select Tb_station.iiiii as '站点号',
Tb_station.tzmc as '台站名称',
avg(Tb_qxcydek.r) as '2001年降水量平均值'
from Tb_qxcydek,Tb_station
where Tb_qxcydek.iiiii = Tb_station.iiiii and (Tb_qxcydek.datedek >= 200101 and Tb_qxcydek.datedek <= 200105)
group by Tb_station.tzmc,Tb_station.iiiii
having Tb_station.iiiii in ('58015','58016','58102','58107','58108','58109')
order by Tb_station.iiiii,Tb_station.tzmc

)
as b
where a.站点号=b.站点号
order by 站点号

回答2:

UNION 操作符用于合并两个或多个 SELECT 语句的结果集。
请注意,UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。
SQL UNION 语法
SELECT column_name(s) FROM table_name1
UNION (ALL)
SELECT column_name(s) FROM table_name2

注:默认,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。

回答3:

横向用JOIN
纵向用UNION

回答4:

空行那行加union 把前面一段\后面一段括起来...