我有两个表
A表:
id   name
1    苹果
2    香蕉
3    葡萄B表:typeId指明是苹果、香蕉、还是葡萄。在实际中name中没有表明是什么水果,通过typeId来辨别。
id    name       typeId    color
1    美国香蕉      2       红色
2    中国香蕉      2       绿色
3    非洲苹果      1       红色
4    印度苹果      1       红色
5    中国苹果      1       绿色
6    美国葡萄      3       红色
7    中国葡萄      3       黄色
8    非洲葡萄      3       绿色
我想通过一个sql语句得到第三个表:统计每种水果,不同颜色的数量
name    红色(数量)   绿色(数量)     黄色(数量)
苹果        2           1             0
香蕉        1           1             0
葡萄        1           1             1这样的sql语句该怎么写呢,大家帮助!谢谢

解决方案 »

  1.   

    declare @a table(id int,name varchar(8))
    insert @a select 1,'苹果'
    union all select 2,'香蕉'
    union all select 3,'葡萄'declare @b table(id int,name varchar(8),typeid int ,color varchar(5))
    insert @b 
    select 1,'美国香蕉',2,'红色' union all
    select 2,'美国香蕉',2,'绿色' union all
    select 3,'美国香蕉',1,'红色' union all
    select 4,'美国香蕉',1,'红色' union all
    select 5,'美国香蕉',1,'绿色' union all
    select 6,'美国香蕉',3,'红色' union all
    select 7,'美国香蕉',3,'黄色' union all
    select 8,'美国香蕉',3,'绿色' select name,红色数量=(select count(1) from (select a.name,b.color,b.typeid from @b b left join @a a on a.id=b.typeid) ac where ac.name=ab.name and ac.color='红色')
     ,绿色数量=(select count(1) from (select a.name,b.color,b.typeid from @b b left join @a a on a.id=b.typeid) ac where ac.name=ab.name and ac.color='绿色')
     ,黄色数量=(select count(1) from (select a.name,b.color,b.typeid from @b b left join @a a on a.id=b.typeid) ac where ac.name=ab.name and ac.color='黄色')
    from (
    select a.name,b.color,b.typeid from @b b left join @a a on a.id=b.typeid) ab
    group by name
    ****************************
    苹果 2 1 0
    葡萄 1 1 1
    香蕉 1 1 0
      

  2.   

    jackeyabc,谢谢你,我是刚学的,在有pHP做网站,你写的是一个存储过程吧。在php中,我还不知道怎么用呢。只会用sql语句!另外,表A中水果的品种会比较多,而且是会变化的,能有一个sql语句实现吗?