获取表格中的第一个和最后一个记录

时间:2016-12-01 18:43:28

标签: google-bigquery

我有不同的STime和ETime的Id1和Id2。对于Id1和Id2的每一组,我倾向于获得第一个和最后一个记录(如输出中所示)。 我尝试使用Id1和Id2对表进行分区,并使用asc和desc命令对其进行排序:

struct configurations *read_file(char * file_name)
{ 
    FILE *f = fopen(file_name ,"r");
    if(!f)
    {
        printf("**********Unable to open config.txt*********");
        return NULL;
    }

    int i, prev, count;
    char *line = NULL, buff[480] = {'\0'};
    size_t len;

    struct configurations *config = (struct configurations *) malloc(sizeof(struct configurations));

    while (getline(&line,&len,f) != -1)
    {
        if(!strncmp("SERVERPORT = ",line,strlen("SERVERPORT = "))){
            config->server_Port = atoi(strstr(line, " = ")+3);
        }
        else if(!strncmp("SCHEDULING = ",line,strlen("SCHEDULING = "))){
            strcpy(config->sched,strstr(line, " = ") + 3);


        }

我没有按预期得到结果。

ROW_NUMBER() OVER(PARTITION BY B.HardwareId, A.TripId ORDER BY StartTime) AS first_record,
ROW_NUMBER() OVER(PARTITION BY B.HardwareId, A.TripId ORDER BY StopTime DESC) AS last_record

1 个答案:

答案 0 :(得分:1)

原始问题中的查询与您以后的评论不完全匹配,但仍然可以帮助您实现目标

尝试

SELECT
   A.Id AS Id,
   StartTime,
   StopTime,
   Latitude,
   Longitude
FROM (
  SELECT
   A.Id AS Id,
   StartTime,
   StopTime,
   Latitude,
   Longitude,
   ROW_NUMBER() OVER(PARTITION BY id ORDER BY StartTime) AS first_record,
   ROW_NUMBER() OVER(PARTITION BY id ORDER BY StartTime DESC) AS last_record
  FROM
   Tb1.Ids  AS A
  JOIN
   Tb2.Points AS B
  ON
   A.StartTime <= B.DateTime
   AND A.StopTime >= B.DateTime
   AND A.HardwareId = B.HardwareId
  WHERE
   (A._PARTITIONTIME BETWEEN TIMESTAMP('2016-11-23')
    AND TIMESTAMP('2016-11-23'))
   AND A.Id IN (334)
)
WHERE first_record = 1 OR last_record = 1  

这里想要在内部查询中添加两个字段,这些字段将编号从开始和结束的所有行

   ROW_NUMBER() OVER(PARTITION BY id ORDER BY StartTime ) AS first_record,
   ROW_NUMBER() OVER(PARTITION BY id ORDER BY StartTime DESC) AS last_record

而不是留下第一行和最后一行

WHERE first_record = 1 OR last_record = 1