COUNT(DISTINCT(UserID)) 可以加条件吗?

cjw227 2013-03-07 08:31:06
表数据如下:

userid money userType
------------------------------------------
A 2 1
A 1 1
A 1 2



我想搜,userType=1的用户数。

select COUNT(DISTINCT(userid)) from table


怎么加条件判断?
...全文
820 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
szm341 2013-03-07
  • 打赏
  • 举报
回复
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
cjw227 2013-03-07
  • 打赏
  • 举报
回复
引用 8 楼 szm341 的回复:
那你group by time,userid把用户加进去喽,啥叫不重复的用户数啊 你提问题不能一次性说全吗? 如果你是按type来定所谓的重复与否,那么每个type即1个数据,写个常量1代替count()
不重复的用户数 ,是指 同一个userid只算作 1。 如表结构中的记录,有3条 userid为A的数据。当userid=1 的时候,用户数为1(而不是2),userid=2的时候,用户数为1
szm341 2013-03-07
  • 打赏
  • 举报
回复
那你group by time,userid把用户加进去喽,啥叫不重复的用户数啊 你提问题不能一次性说全吗? 如果你是按type来定所谓的重复与否,那么每个type即1个数据,写个常量1代替count()
cjw227 2013-03-07
  • 打赏
  • 举报
回复
引用 6 楼 szm341 的回复:
你要是usertype不定的话就要写动态语句拼接了 SQL code?1234567select 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 ……
感谢。其实这一步我写出来的。 但是这边考虑到,用户数 应该是 经过DISTINCT以后的数据,即:不重复的用户数。 上面的代码,暂时做不到这点吧
szm341 2013-03-07
  • 打赏
  • 举报
回复
你要是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
cjw227 2013-03-07
  • 打赏
  • 举报
回复
引用 4 楼 szm341 的回复:
SQL code?123select userType,time as 日期,count(1) as 数量,sum(money)moneyfrom tb where userType=1group by userType,time
如果我要在语句中,同时统计 userType=2的人数呢? 就是: 日期 userType=1的money userType=1的用户数 userType=2的用户数 --------------------------------------------------------------------------------------------------
szm341 2013-03-07
  • 打赏
  • 举报
回复

select userType,time as 日期,count(1) as 数量,sum(money)money
from tb where userType=1
group by userType,time
cjw227 2013-03-07
  • 打赏
  • 举报
回复
可能我没说清楚 表数据如下: 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的用户数 的数据怎么求?
szm341 2013-03-07
  • 打赏
  • 举报
回复
高科技啊不加where,即便掌握这种技巧也不实用啊。。
cjw227 2013-03-07
  • 打赏
  • 举报
回复
不用where

34,837

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧