Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计算SQL中的重复次数_Sql_Sql Server_Tsql - Fatal编程技术网

计算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)

什么决定“之后”?我没有看到任何列可以决定数据的顺序。还有一列日期决定了顺序?@HABO我用我的代码/ideaThanks更新了问题,这是类似于我的解决方案,它有相同的问题。执行查询5分钟后,我仍然没有结果。在一年的时间里花了三分钟你看到我的最后一个要点了吗?(添加索引,然后查看性能)。另外,这两组数字是动态的吗?他们是由什么决定的?我会使用索引表,这样你的性能会更好。我会在上面的评论之后发布你的更新。有问题的表是根据上一个查询生成的。我将创建临时表并在其上设置索引,并在执行主查询后删除它。谢谢你的帮助!!
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