高分相送,一个很经典的SQL语句,是高手就进来讨论下!
表A 
 ID      COL1      COL2 
 1            0.5            SDS 
 2            2                  SD 
 3            1.5            FG 
 4            1                  GG 
 5            4                  GGH 
 ------------------------- 
 表B 
 ID         A         B      C               FLAG 
 1         12      200   300      1 
 1         13      300   400      0 
 3         14      400   500      0 
 4         22      500   600      0   
 表A与表B必须关联,且得按ID分组,写条SQL语句,查询出如下结果 
 (不能使用其他存储或者函数) 
 ---------------------------------------- 
 ID   |   A.COL1   |按flag=1统计A次数|按flag=1统计A次数|   B求和      | 
 1            0.5            1                                                            0                                             500 
 2            2                  0                                                            0                                             0 
 3            1.5            0                                                            1                                             400 
 4            1                  0                                                            1                                             500 
 5            4                  0                                                            0                                             0
------解决方案--------------------怎么有2列 "按flag=1统计A次数 ",什么意思?
------解决方案--------------------1   13  300 400  0 --> 0是1吧? 
 按flag=1统计A次数| B求和 --> 是flag=0吧 
 好难明白
------解决方案--------------------是个好题目,顶下先
------解决方案--------------------是不是你要的结果?   
 select a.id,a.col1,isnull(bb.c_a,0),isnull(cc.c_a,0),isnull(dd.b_sum,0) from a, 
 (select id,c_a=count(*) from b where flag= '1 ' group by id) bb, 
 (select id,c_a=count(*) from b where flag= '0 ' group by id) cc, 
 (select id,b_sum=sum(B) from b group by id) dd  
 where 
 a.id*=bb.id and a.id*=cc.id and a.id*=dd.id
------解决方案--------------------