简体   繁体   English

在SQL中选择每第n条具有条件的行

[英]Selecting every nth row with a condition in SQL

This seems a conceptually easy question, but with no straightforward answer. 这似乎是一个概念上很简单的问题,但没有简单的答案。

I have some time-serious data, with a whole bunch (millions) of unique events given by the event_ID variable, describing a set (of several) physical properties (phys_props). 我有一些非常耗时的数据,其中有event_ID变量给出的一整堆(数百万)唯一事件,描述了一组(数个)物理属性(phys_props)。

I'm writing SQL and want to return every nth row (where I have freedom to choose n to be eg 5, 1000, 10000 etc.) for this time-series dataset. 我正在编写SQL,并想为该时间序列数据集返回每第n行(我可以自由选择n,例如5、1000、10000等)。

However, if eg n=1000 and there are less than 1000 records for a given physical property, I don't want to return the event_ID records there at all. 但是,如果例如n = 1000且给定物理属性的记录少于1000条,那么我根本就不希望返回event_ID记录。

Something like: 就像是:

SELECT * 
FROM myTable
WHERE MOD(myTable, 1000) = 0 

is my starting point. 是我的出发点。

you can give an unique no to each of the row, and then do the calculation on the unique no. 您可以为每行赋予唯一编号,然后对唯一编号进行计算。 Something like this 像这样

with t as(    
select *,row_number() over (order by event_ID) SN from the_table_name
)

select * from t where SN%100=0

You can try something like this: 您可以尝试如下操作:

SELECT * FROM 
(SELECT EVENT_ID,  
       @rownum := @rownum + 1 AS rank
FROM myTable, 
       (SELECT @rownum := 0) r
) ds
WHERE MOD(rank, 5) = 0
;

You can try this: 您可以尝试以下方法:

         Select * from myTable
         Having mod(count(*), 1000)=0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM