日期:2014-05-18  浏览次数:20401 次

超级难的SQL查询求高手
见贴
http://topic.csdn.net/u/20120203/15/a141ab76-a6b0-4f8b-a02e-de3ac92f5bd1.html

------解决方案--------------------
你只是给出了两个表,但是根据你的说明,不知道你想要什么样的结果?
------解决方案--------------------
把你要的结果贴出来
------解决方案--------------------
SQL code

declare @表AAA table (ID int,TITLE varchar(2),USERName varchar(3))
insert into @表AAA
select 1,'t1','U1' union all
select 2,'t2','U2' union all
select 3,'t3','U5' union all
select 4,'t1','U7' union all
select 5,'t8','U12' union all
select 6,'t2','U12'

declare @表BBB table (ID int,TITLE varchar(2),TJ int,USERName varchar(3))
insert into @表BBB
select 1,'t1',2,'u1' union all
select 2,'t1',1,'u1' union all
select 3,'t1',3,'U2' union all
select 4,'t2',5,'U2' union all
select 5,'t5',1,'U3' union all
select 6,'t3',2,'u1' union all
select 7,'t1',6,'u12'

--不明白要谁升序,谁降序
select *,
(select sum(TJ) from @表BBB 
where title=a.title and username=a.username) as B表中的TJ和
from @表AAA a order by 4 
/*
ID          TITLE USERName B表中的TJ和
----------- ----- -------- -----------
3           t3    U5       NULL
4           t1    U7       NULL
5           t8    U12      NULL
6           t2    U12      NULL
1           t1    U1       3
2           t2    U2       5
*/

------解决方案--------------------
你表达得不清楚,把你想要的数据贴出来,看到效果就知道怎么写了