表数据如下:            userid       money    userType
------------------------------------------
          A            2          1
          A            1          1
          A            1          2我想搜,userType=1的用户数。select COUNT(DISTINCT(userid)) from table怎么加条件判断?

解决方案 »

  1.   

    高科技啊不加where,即便掌握这种技巧也不实用啊。。
      

  2.   

    可能我没说清楚
    表数据如下:            userid       money    userType    time
    -------------------------------------------------------
              A            2          1           2013-03-07
              A            1          1           2013-03-07
              A            1          2           2013-03-07我要分析每天的数据:日期       userType=1的money           userType=1的用户数
    ----------------------------------------------------------------------
    select CONVERT(VARCHAR(19),time,111) as 日期,
      SUM(case when userType=1 then  money else 0 end)  as   userType=1的money
      from table
    group by CONVERT(VARCHAR(19),time,111)
    请问  userType=1的用户数  的数据怎么求?
      

  3.   


    select userType,time as 日期,count(1) as 数量,sum(money)money
    from tb where userType=1
    group by userType,time
      

  4.   


    如果我要在语句中,同时统计 userType=2的人数呢?就是:日期       userType=1的money           userType=1的用户数      userType=2的用户数
    --------------------------------------------------------------------------------------------------
      

  5.   

    你要是usertype不定的话就要写动态语句拼接了select time as 日期
    ,SUM(case when userType=1 then  1  else 0 end) as user1数量
    ,SUM(case when userType=1 then  money else 0 end) user1money
    ,SUM(case when userType=2 then  1  else 0 end) as user2数量
    ,SUM(case when userType=2 then  money else 0 end) user2money
    from tb 
    group by time
      

  6.   


    感谢。其实这一步我写出来的。
    但是这边考虑到,用户数 应该是 经过DISTINCT以后的数据,即:不重复的用户数。上面的代码,暂时做不到这点吧
      

  7.   

    那你group by time,userid把用户加进去喽,啥叫不重复的用户数啊
    你提问题不能一次性说全吗?如果你是按type来定所谓的重复与否,那么每个type即1个数据,写个常量1代替count()
      

  8.   


    不重复的用户数 ,是指 同一个userid只算作 1。
    如表结构中的记录,有3条 userid为A的数据。当userid=1 的时候,用户数为1(而不是2),userid=2的时候,用户数为1
      

  9.   

    select userid,time as 日期
    ,1 as user1数量
    ,SUM(case when userType=1 then  money else 0 end) user1money
    ,1 as user2数量
    ,SUM(case when userType=2 then  money else 0 end) user2money
    from tb 
    group by userid,time