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

请高手帮解决sql嵌套查询 排序的问题
现有两个表AAA和表BBB

表AAA (title可能是重复的这是商家发布的)
ID TITLE USER(用户)
1 t1 U1
2 t2 U2
3 t3 U5
4 t1 U7
5 t8 U12
6 t2 U12
......

表BBB (是user的用户销售title产品的TJ销售数量)
ID TITLE TJ(销售数量) USER(用户)
1 t1 2 u1
2 t1 1 u1
3 t1 3 U2
4 t2 5 U2
5 t5 1 U3
6 t3 2 u1
7 t1 6 u12
......

想要的效果是查询表AAA的title和user"按照"对应表BBB中title和user的TJ总数来排序(表BBB中不存在的也作为条件,一个是升序,一个降序)
这样还有个问题,下面能把对应的值输出来吗?
例如
<%=rs("id")%> <%=rs("title")%> <%=总的销售数量%>(好像有点难啊)
小弟只会ASP而且比较菜,遇到这么个头大的问题,搞了大半天了也搞不出来,求高手帮帮忙呀?

------解决方案--------------------
SQL code
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

------解决方案--------------------
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
*/

------解决方案--------------------
SQL code
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