取最大的一条
Table A
a1 NVRCHAR(10),
a2 NVRCHAR(10),
a3 NVRCHAR(10)
Table B
b1 NVRCHAR(10),
b2 NVRCHAR(10),
b3 NVRCHAR(10)
SELECT *
FROM A
INNER JOIN B
ON A.a1 = B.b1
where A.a2 = '1'
在这个基础上我还想加一个条件就是取A.a3最大的那条,要怎么写呀
方案一
SELECT *
FROM A
INNER JOIN B
ON A.a1 = B.b1
WHERE A.a2 = '1'
AND A.a3 =
(
SELECT MAX(A.a3)
FROM A
INNER JOIN B
ON A.a1 = B.b1
WHERE A.a2 = '1'
)
方案二
DECALRE A3_MAX NVRCHAR(10)
SELECT A3_MAX = MAX(A.a3)
FROM A
INNER JOIN B
ON A.a1 = B.b1
WHERE A.a2 = '1'
SELECT *
FROM A
INNER JOIN B
ON A.a1 = B.b1
WHERE A.a2 = '1'
AND A.a3 = A3_MAX
还有没有更好点的方法呀,执行的结果应该是可能有N条的情况,
所以用ORDERBY,然后top1好像也不行
------解决方案--------------------
--> 测试数据: @TableA
declare @TableA table (a1 int,a2 int,a3 varchar(1))
insert into @TableA
select 1,2,'a' union all
select 1,3,'b' union all
select 2,2,'c' union all
select 2,3,'d' union all
select 3,1,'e' union all
select 3,3,'f'
--> 测试数据: @TableB
declare @TableB table (b1 int,b2 int,b3 varchar(1))
insert into @TableB
select 1,2,'a' union all
select 1,3,'b' union all
select 2,2,'c' union all
select 2,3,'d' union all
select 3,1,'e' union all
select 3,3,'f'
select * from @TableA a inner join @TableB b
on a.a1='1' where b.b1='2' and a.a3=(select max(a3) from @TableA where a1='1')
/*
a1 a2 a3 b1 b2 b3
----------- ----------- ---- ----------- ----------- ----
1 3 b 2 2 c
1 3 b 2 3 d
*/
------解决方案--------------------没看懂,能把你的数据也列出来么?
------解决方案--------------------SELECT * FROM (SELECT a1,a2,MAX(a3) AS a3 FROM A WHERE a2='1' GROUP BY a1,a2) a INNER JOIN B b ON a.a1=b.b1