计算SQL中的重复次数
我试图解决一个问题,但没有成功 我有两张号码表计算SQL中的重复次数,sql,sql-server,tsql,Sql,Sql Server,Tsql,我试图解决一个问题,但没有成功 我有两张号码表 {1,2,3,4} {5,6,7,8,9} 我有一张桌子 ID Number 1 1 1 2 1 7 1 2 1 6 2 8 2 7 2 3 2 9 现在我需要计算第二个列表中的数字在第一个列表中的数字之后有多少次,但我应该只逐个计算id 在上面的示例表中,结果应该是2 三个匹配的PAR,但因为我们只有两个不同
{1,2,3,4}
{5,6,7,8,9}
我有一张桌子
ID Number
1 1
1 2
1 7
1 2
1 6
2 8
2 7
2 3
2 9
现在我需要计算第二个列表中的数字在第一个列表中的数字之后有多少次,但我应该只逐个计算id
在上面的示例表中,结果应该是2
三个匹配的PAR,但因为我们只有两个不同的ID,所以结果是2而不是3
PAR:
注意。我使用MSSQL
编辑。还有一列日期决定了订单 Edit2-解决方案 我写这个查询
SELECT * FROM table t
left JOIN table tt ON tt.ID = t.ID
AND tt.Date > t.Date
AND t.Number IN (1,2,3,4)
AND tt.Number IN (6,7,8,9)
在此之后,我计划按id分组,每个id只使用一个匹配项,但执行需要很多时间
select a.id, min(a.number) as a, min(b.number) as b
from mytable a
inner join mytable b
on a.id = b.id
and a.date < b.date
and b.number in (5,6,7,8,9)
where a.number in (1,2,3,4)
group by a.id
因此,两对数据分别在一行上输出,值a属于第一组数字,列b的值属于第二组数字
这是一个
对尝试的评论(编辑2至问题)
稍后,您在问题中添加了一个查询尝试。关于这一尝试的一些评论:
- 您不需要
,因为您确实希望两个值都匹配<代码>内部联接通常具有更好的性能,因此请使用它左联接
- (1,2,3,4)中的条件
t.Number不属于
子句中。结合on
,结果将包括违反此条件的左连接
记录。它应该放在t
子句中where
- 您对性能的担忧可能是有道理的,但可以通过在表上添加一个有用的索引来解决,即在
或(id,number,date)
(id,date,number)
2 3
2 9
SELECT * FROM table t
left JOIN table tt ON tt.ID = t.ID
AND tt.Date > t.Date
AND t.Number IN (1,2,3,4)
AND tt.Number IN (6,7,8,9)
select a.id, min(a.number) as a, min(b.number) as b
from mytable a
inner join mytable b
on a.id = b.id
and a.date < b.date
and b.number in (5,6,7,8,9)
where a.number in (1,2,3,4)
group by a.id
id a b
1 1 6
2 3 9