ID mobileno dateofregistration registrationstate
44 1674174925 2011-04-18 10:17:30.670 0
45 1677864168 2011-04-18 10:20:22.450 1
46 1677864161 2011-04-18 20:47:35.293 0
47 1674174925 2011-04-19 09:28:55.200 1
48 1674174925 2011-04-19 09:28:56.200 0
49 1674174925 2011-04-19 09:28:57.200 1
50 1674174925 2011-04-18 10:17:30.670 0
51 1677864168 2011-04-18 10:20:22.450 1
52 1677864161 2011-04-20 20:47:35.293 0
53 1674174925 2011-04-22 09:28:55.200 1
54 1674174925 2011-04-28 09:28:56.200 0
55 1674174925 2011-04-28 09:28:57.200 1
我的问题是如何使用以下条件计算行数:
个人手机号码 registrationstate = 1
和datediff(day,dateofregistration) > 30
这里的结果将是1
答案 0 :(得分:0)
首先,datediff
需要3个参数
DATEDIFF ( datepart , startdate , enddate )
我认为您想与今天的日期进行比较,因此您可以使用getdate()
select * from yourtable
where registrationstate = 1
and datediff( day, dateofregistration, getdate() ) > 30
如果getdate()
返回2011-05-04,您将获得以下输出
------------------------------------------------------------
ID mobileno dateofregistration registrationstate
------------------------------------------------------------
45 1677864168 2011-04-18 10:20:22.450 1
47 1674174925 2011-04-19 09:28:55.200 1
49 1674174925 2011-04-19 09:28:57.200 1
51 1677864168 2011-04-18 10:20:22.450 1
53 1674174925 2011-04-22 09:28:55.200 1
55 1674174925 2011-04-28 09:28:57.200 1
------------------------------------------------------------
现在您希望按mobileno
对结果进行分组,并返回每个组的行数。您可以使用COUNT(*)
聚合函数返回每组的行数
select COUNT(*) as total, mobileno from yourtable
where registrationstate = 1
and datediff( day, dateofregistration, getdate() ) > 30
group by mobileno
您将获得以下输出
------------------------------------------------------------
mobileno total
------------------------------------------------------------
1677864168 2
1674174925 4
------------------------------------------------------------