求一条两表联合查询最小值的SQL语句,多谢
求一条两表联合查询最小值的SQL语句,谢谢!
表1:
COL1 COL2
1 1
1 2
1 3
2 1
2 2
2 3
表2:
COL1 COL2
1 1
需求:根据表2要找出表1中的最小值(COL2先,然后COL1)
比如:在表2中,1、1这个行数据使用过了,我就要从表1中找出 2、1这行数据插入到表2中去,然后再查询,再将表1中的 1、2这行数据找出来,只求一条SQL查询语句即可,谢谢!
------解决方案--------------------
------解决方案--------------------
2005以上版本
select col1,col2 from
(select *,rn=row_number()over (order by col2,col1) from 表1 b where not exists
(select * from 表2 a where a.col1=b.col1 and a.col2=b.col2)) a
where rn=1
表1:
COL1 COL2
1 1
1 2
1 3
2 1
2 2
2 3
表2:
COL1 COL2
1 1
需求:根据表2要找出表1中的最小值(COL2先,然后COL1)
比如:在表2中,1、1这个行数据使用过了,我就要从表1中找出 2、1这行数据插入到表2中去,然后再查询,再将表1中的 1、2这行数据找出来,只求一条SQL查询语句即可,谢谢!
------解决方案--------------------
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-18 11:20:22
-- Verstion:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go
create table [a]([COL1] int,[COL2] int)
insert [a]
select 1,1 union all
select 1,2 union all
select 1,3 union all
select 2,1 union all
select 2,2 union all
select 2,3
--> 测试数据:[b]
if object_id('[b]') is not null drop table [b]
go
create table [b]([COL1] int,[COL2] int)
insert [b]
select 1,1
--------------开始查询--------------------------
SELECT
MIN(a.col1) AS col1, b.COL2
FROM
(SELECT
*
FROM
a
WHERE
NOT EXISTS ( SELECT
1
FROM
b
WHERE
col1=a.col1 AND col2=a.col2 )) a
INNER JOIN b ON a.COL2=b.col2
GROUP BY
b.COL2
----------------结果----------------------------
/* col1 COL2
----------- -----------
2 1
*/
------解决方案--------------------
2005以上版本
select col1,col2 from
(select *,rn=row_number()over (order by col2,col1) from 表1 b where not exists
(select * from 表2 a where a.col1=b.col1 and a.col2=b.col2)) a
where rn=1