当前位置: 代码迷 >> Oracle管理 >> 这个 SQL 统计语句如何写
  详细解决方案

这个 SQL 统计语句如何写

热度:574   发布时间:2016-04-24 04:21:43.0
这个 SQL 统计语句怎么写?
tableA
uid      uname
1          test1
2          test2
3          test3
4          test4
n          testN

tableB
id               name       type         uid       
1                 a1                1             1
2                 a2                1             1
3                 a 3               2             1
4                 a 4               1             2
5                 a5                1             2
6                 a6                1             2
7                 a7                1             3
8                 a8                2             3

要统计:
每个uid的type有多种(如uid=1的type有1、2两种)的情况的和。
就拿上述例子来说,uid=1的type有两种(1和2),uid=2的type只有一种(即type都是1),uid=3的type也有两种(1和2)
所以统计的结果是:1+0+1=2

这样的sql语句怎么写?谢谢!
------解决方案--------------------
我的思路是先筛选出相同uid不同type的的记录,在在上面的结果集中统计每个uid 的type类型的数目,
最后计算type大于1的记录条数值。

select count(u_id)
  from (select u_id, count(u_id) as num
          from (select distinct (type_no), u_id from tableb order by u_id) a
         group by u_id) b
 where num > 1;

  相关解决方案