!!!!!!求一sql语句!!!!!!!!(50分)

  • 主题发起人 主题发起人 fhuibo
  • 开始时间 开始时间
F

fhuibo

Unregistered / Unconfirmed
GUEST, unregistred user!
表 A 有两个字段 &nbsp; (其中ff字段是2-20位不等的字符串,没有规律)<br>ff(字符) &nbsp;cc(int)<br>01 &nbsp; &nbsp; &nbsp; &nbsp; 3<br>01 &nbsp; &nbsp; &nbsp; &nbsp; 2<br>0102 &nbsp; &nbsp; &nbsp; 4<br>010201 &nbsp; &nbsp; 8<br>0103 &nbsp; &nbsp; &nbsp; 5<br>02 &nbsp; &nbsp; &nbsp; &nbsp; 2<br>0201 &nbsp; &nbsp; &nbsp; 3<br>0201 &nbsp; &nbsp; &nbsp; 4<br>我想按ff分组求 cc的合计 但要包含下级的代码,比如 01 要把以 01 开头的都 sum 起来<br>0102 要把以 0102 开头的sum 起来,02 的要把以 02 开头的sum起来。。。。。。<br>要求结果:<br>ff &nbsp; &nbsp;cc<br>01 &nbsp; &nbsp;22<br>0102 &nbsp;12<br>010201 8<br>0103 &nbsp; 5<br>02 &nbsp; &nbsp; 9<br>0201 &nbsp; 7
 
select ff,sum(cc) as cc from 表  group by &nbsp;left(ff,2)<br>union all<br>select ff,sum(cc) as cc from 表 group by &nbsp;left(ff,4)<br>union all<br>select ff,sum(cc) as cc from 表 group by &nbsp;left(ff,6)<br>union all<br>select ff,sum(cc) as cc from 表 group by &nbsp;left(ff,8)
 
楼上大哥,忘了告诉你,我的ff字段 是没有规律的,并且还是变化的。也就是说2-20位是不等的,再说了你的sql语句能执行吗?
 
规律是不是len(ff)&lt;len(ff1) and ff1 like 'ff%'?<br>select ff,Sum(cc) from<br>(<br>select tb.ff,ttt.* from tb left join (select * from tb) ttt on len(tb.ff) &lt;= len(ttt.ff) and ttt.ff like tb.ff+'%' <br>) ttttt<br>Group By ff
 
如果数据量小的话 用一个SQL解决是可行的 虽然麻烦点 分别汇总2-20位 (19个语句联合下)<br>奉劝你另外做一张汇总表,逐条记录累加即可
 
select ff, sum(cc) from TABLE group by ff order by ff; 即可 因为ff是字符型,排序的话就是按照你要求的排的。oracle下测试通过。
 
我的SQL 不能执行?  如果是SQLSERVER是问题的.<br><br>而且这只是是思路而已, 不会有现成的东西  拿过来复制粘贴就可以用的, 另外我觉得  表结构还是可以再修改的,  应该有一个字段来描述ff的层次 , 这样会好些.  静待高手提供的SQL.
 
SELECT ff,<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (SELECT SUM(cc)<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;FROM TABLE1<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;WHERE ff LIKE a.ff + '%') AS cc<br>FROM TABLE1 a<br>GROUP BY ff
 
group by ff having(Count(*))&gt;0
 
select ff,sum(cc )from A<br>group by ff
 
SELECT ff,<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (SELECT SUM(cc)<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;FROM TABLE1<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;WHERE ff LIKE a.ff + '%') AS cc<br>FROM TABLE1 a<br>GROUP BY ff
 
多人接受答案了。
 

Similar threads

回复
0
查看
1K
不得闲
回复
0
查看
848
不得闲
D
回复
0
查看
1K
DelphiTeacher的专栏
D
D
回复
0
查看
825
DelphiTeacher的专栏
D
D
回复
0
查看
579
DelphiTeacher的专栏
D
后退
顶部