您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

sql union 查询实现复杂查询

2024/4/16 1:48:33发布18次查看
union是一个联合查询,他可以选择2个或更多的表的数据集进来各类操作,有时我们要过滤重复等都是可以的,好面来看看实例吧。
union查询,让您结合2个或更多的“选择”查询的结果集。它消除了各种“选择”报表之间的重复行。
每个内部查询的sql语句必须在结果中相同的字段数套类似的数据类型。
union查询的语法是:
 代码如下 复制代码
field1, field2, . field_n
from tables
union
select field1, field2, . field_n
from tables;
example #1
the following is an example of a union query:
 代码如下 复制代码
select supplier_id
from suppliers
union
select supplier_id
from orders;
在这个例子中,如果supplier_id出现在供应商和订单表,它会出现在您的结果集一次。会删除重复内容。
例#2 - order by子句
下面是一个union查询,使用order by子句
代码如下 复制代码
select supplier_id, supplier_name
from suppliers
where supplier_id > 2000
union
select company_id, company_name
from companies
where company_id > 1000
order by 2;
问:我需要比较两个日期和返回日期值的基础上的一个字段计数。例如,我在一个表的日期字段称为最后更新日期。我要检查,如果trunc(last_updated_date> = trunc(sysdate- 13)。
答:由于您使用的是这是一个聚合函数count函数,我们建议你使用union查询。例如,你可以尝试以下方法:
 代码如下 复制代码
select a.code as code, a.name as name, count(b.ncode)
from cdmaster a, nmmaster b
where a.code = b.code
 and a.status = 1
 and b.status = 1
 and b.ncode 'a10'
 and trunc(last_updated_date) group by a.code, a.name
union
select a.code as code, a.name as name, count(b.ncode)
from cdmaster a, nmmaster b
where a.code = b.code
 and a.status = 1
 and b.status = 1
 and b.ncode 'a10'
 and trunc(last_updated_date) > trunc(sysdate-13)
group by a.code, a.name;
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product