日期:2014-05-18 浏览次数:20443 次
select a.* from AAA a left join (select [USER], TITLE, sum(TJ)TJ from BBB group by [USER], TITLE) b on a.[USER]=b.[USER] and a.TITLE=b.TITLE order by b.TJ
------解决方案--------------------
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 */
------解决方案--------------------
create table A(ID int,TITLE varchar(10),[USER] varchar(10)) insert A select 1,'t1','U1' union all select 2,'t2','U2' union all select 3,'t3','U12' union all select 4,'t5','U7' union all select 5,'t1','U2' union all select 6,'t2','U12' create table B(ID int,TITLE varchar(10),TJ int,[USER] varchar(10)) insert B 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, 'U7' union all select 6, 't2', 6, 'u12' union all select 8, 't2', 4, 'u2' go select A.ID,A.Title,A.[User],TJ=sum(isnull(b.TJ,0)) from A left join B on B.[user]=A.[user] and B.Title=A.Title group by A.ID,A.Title,A.[User] order by sum(isnull(b.TJ,0)) desc /* ID Title User TJ ---- ---- ---- -- 2 t2 U2 9 6 t2 U12 6 5 t1 U2 3 1 t1 U1 3 4 t5 U7 1 3 t3 U12 0 */ go drop table A,B