TSQL计数不同

时间:2018-06-30 08:37:47

标签: sql tsql select count distinct

我正在尝试从表中获取唯一值,该表包含以下内容作为时间日志文件:

id | time | code | user
1  | 7000 | xxxx | 1 
2  | 7000 | xxxx | 1
3  | 7500 | xxxx | 2
4  | 7000 | xxxx | 3

我想知道有多少唯一用户当时使用过该代码,例如7000,应该说2,但我写的与众不同,我得到3

SELECT Time, COUNT(*) as total, Code
FROM dbo.AnalyticsPause
WHERE CODE = 'xxxx'
GROUP BY  id, Time, Code

结果:

time | Count | code 
7000 | 3     | xxxx
7500 | 1     | xxxx

我想去的地方

time | Count | code 
7000 | 2     | xxxx
7500 | 1     | xxxx

我如何能够在id_user上添加一个非重复的内容,并且仍然一直在一起计数

1 个答案:

答案 0 :(得分:7)

count(*)计算行数(在组中)。您应该只计算distinct user

SELECT   Time, COUNT(DISTINCT user) as total, Code
FROM     dbo.AnalyticsPause
WHERE    code = 'xxxx'
GROUP BY Time, Code