当前位置: 代码迷 >> ASP.NET >> 求个统计sql解决方法
  详细解决方案

求个统计sql解决方法

热度:4284   发布时间:2013-02-25 00:00:00.0
求个统计sql
用户表 U0
A1 A2  
1 101  
2 102
3 1001
4 1002
.....

市级表 U1
A1 A2 A3(用户表A2)
1 珠海市 101 
2 汕头市 102
3 .... ...


县级表 U2

A1 A2 A3(市级表A1) A4 (用户表A2)
1 斗门区 1 1001
2 金湾区 1 1002
....
新闻表 N1
A1 A2(用户表A1) A3(0未采纳 1采纳) A4 A5
1 1 1 标题 内容
2 2 0 ....
3 2 1 ....
4 3 0 ....

要求统计结果
单位 发文总数 采纳数 
珠海市 1 1
斗门区 2 1
金湾区 1 0
珠海市综合统计 4 2
....

求高手
 

------解决方案--------------------------------------------------------
SQL code
;with cte as(  select  x.a1 as 市 , n.a3 as 状态  from  新闻表 n inner join 用户表 u on n.a2=u.a1   inner join 市级表 x on x.a3=u.a2 ), cte2 as(  select  x.a1 as 县 , n.a3 as 状态  from  新闻表 n inner join 用户表 u on n.a2=u.a1   inner join 县级表 x on x.a4=u.a2),cte3 as(select   单位=a2,  发文总数=(select count(1) from cte where c.a1= 市),  采纳=(select count(1) from cte where c.a1= 市 and 状态=1),  c.a1 a1  from 市级表 c  union all  select   单位=a2,  发文总数=(select count(1) from cte2 where c.a1= 县),  采纳=(select count(1) from cte2 where c.a1= 县 and 状态=1),  c.a1  a1  from 县级表 c)select * from cte3 order by  a1
------解决方案--------------------------------------------------------
楼主可参考
------解决方案--------------------------------------------------------
楼上的又让我学到了个新语法。。cte 表达式。。这个看起来蛮好用的。。哈哈。。感谢
  相关解决方案