日期:2014-05-20  浏览次数:20837 次

求一个sql语句写法?
A表 字段为 ID,Name,Quantity,CategoryID(可空),DID
B表 字段为 ID,Name,Quantity,CategoryID(可空)
C表 字段为 CategoryID,CategoryName
D表 字段为 DID,DName(可重复)

如果categoryid不为代的情况下,我的表达式为
select d.dname,c.categoryname ,sum(a.quantity)as Q1 ,sum(b.quantity) as Q2 from a inner join d on d.did=a.did left join c on c.categoryid=a.categoryid full join
b on (b.id=a.id and a.categoryid=c.categoryid) where group by d.dname,c.categoryname 

上面实际上是错误 的,我至所以写这个式子,让你看出我想查询的结果,正确怎么写??


------解决方案--------------------
select d.dname,
c.categoryname ,
sum(a.quantity) as Q1 ,
sum(b.quantity) as Q2 
from a inner join d on d.did = a.did 
left join c on c.categoryid = a.categoryid 
full join b on b.id = a.id 
 where group by d.dname,
c.categoryname 

------解决方案--------------------
实际上是对a,b两个表分别统计,所以可用union,如下:
select d.dname,c.categoryname ,sum(a.quantity)as Q1,'' as Q2 from a 
inner join d on d.did=a.did 
left join c on a.categoryid=c.categoryid 
group by d.dname,c.categoryname
union
select d.dname,c.categoryname ,'',sum(b.quantity)as Q2 from b 
inner join d on d.did=b.did 
left join c on b.categoryid=c.categoryid 
group by d.dname,c.categoryname


------解决方案--------------------
select
d.dname,
c.categoryname ,
sum(a.quantity) as Q1 ,
sum(b.quantity) as Q2 
from a , b, c , d
where a.did = d.did 
and d.did = b.did 
and a.categoryid = c.categoryid 
and b.categoryid = c.categoryid 
group by 
d.dname,
c.categoryname