一个复杂统计问题,要查询from与to字段合并后出现次数在n次以上的结果集 。

有一个数据库表,结构为:(3个字段)
from 从一方 字符型
to 到另一方 字符型
time 时间 时间型

数据:
from to time
111 222 2002-10-10
111 333 2002-10-11
111 444 2002-10-12
111 222 2002-10-13
111 222 2002-10-14
111 333 2002-10-15
222 111 2002-10-16
222 333 2002-10-17
222 555 2002-10-18
444 222 2002-10-19
444 222 2002-10-20
666 222 2002-10-21

要查询from与to字段合并后出现次数在n次以上的结果集

如:
n=2结果集为:
from to time
111 222 2002-10-10
111 333 2002-10-11
111 222 2002-10-13
111 222 2002-10-14
111 333 2002-10-15
444 222 2002-10-19
444 222 2002-10-20

n=3结果集为:
from to time
111 222 2002-10-10
111 222 2002-10-13
111 222 2002-10-14

不知这种情况的SQL语句如何写?
---------------------------------------------------------------

declare @n int
set @n=2 -- change 2 to 3 for the second case

select * from #mytable t1
where
(select count(*)
from #mytable t2
where t2.[from]=t1.[from] and t2.[to]=t1.[to]) >= @n
---------------------------------------------------------------

select * from 你的表 b where exists (select 1 from (select [from],[to] from 你的表 group by [from],[to] having count(*)>=@你的数) a where a.[from]=b.[from] and a.to=b.to)

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus