求解SQL解答
产品表goods(gid name price )
顾客表buyer(bid name)
销售表sales (id gid bid num)
1.查询各个商品各个卖出去了多少钱
2.查询没有买商品A的顾客!
3.查询前三个花钱买商品最多的顾客!
[解决办法]
1.select s.gid,sum(s.num*g.price) as mmfrom sales s,goods gwhere s.gid=g.gidgroup by s.gid2. select b.* from buyer b,sales ss where b.bid=ss.bid and b.bid not in( select bid from sales s where exists (select 1 from goods g where s.gid=g.gid and g.name='A'))3.select s.bid,b.name,sum(s.num*g.price) as mmfrom sales s,goods g,buyer bwhere s.gid=g.gid and b.bid=s.bidgroup by s.bid,b.nameorder by 3limit 3
[解决办法]
贴错了。。。重新贴一次
1.--如果销售记录在sales为空则total = 0select a.gid,a.name,sum(ifnull(a.price*b.num,0)) as total from goods a left join sales b on a.gid = b.gid group by a.gid
[解决办法]
SELECT a.gid,(a.price*b.total) AS total FROM goods a LEFT JOIN (SELECT gid,SUM(num) AS total FROM sales GROUP BY gid) b ON a.gid=b.gid