Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.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,使用SQLServerMgmtStudio。我的数据集如下 ID Days Value Threshold A 1 10 30 A 2 20 30 A 3 34 30 A 4 25 30 A 5 20 30 B 1 5 15 B 2 10 15 B 3 12 15 B 4

使用SQLServerMgmtStudio。我的数据集如下

ID   Days   Value   Threshold
A    1      10      30
A    2      20      30
A    3      34      30
A    4      25      30
A    5      20      30
B    1      5       15
B    2      10      15
B    3      12      15
B    4      17      15
B    5      20      15
我希望运行一个查询,以便仅为每个ID选择达到阈值后的行。此外,我希望创建一个从1开始的新天数列,从该列中选择行。上述数据集的预期输出如下所示

ID   Days   Value   Threshold   NewDayColumn
A    3      34      30              1
A    4      25      30              2
A    5      20      30              3
B    4      17      15              1
B    5      20      15              2
后面几行的数据是否低于阈值无关紧要,我想在阈值超过1时取第一行,并继续计算ID的行数。
谢谢大家!

您可以为此使用窗口函数。这里有一种方法:

select t.*, row_number() over (partition by id order by days) as newDayColumn
from (select t.*,
             min(case when value > threshold then days end) over (partition by id) as threshold_days
      from t
     ) t
where days >= threshold_days;

谢谢,这部分是有帮助的。:)我想在这之后我可以算出行数。@NeilAk。当我阅读问题时,我错过了
row\u number()
部分(更有趣的部分是选择行)。但我确实把它放进去了。