如何从每个id MSSQL的第一行中选择特定范围

时间:2017-07-06 21:25:21

标签: sql-server sql-server-2008

我在html中创建了一个表来显示每个id的第一行,并允许用户选择他们想要查看的特定范围,但不确定如何在查询中编写它。

With results as 
 (
   i.*, 
   ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN] 
   FROM HolidayList AS I
   INNER JOIN (
      SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
   )
   AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
 )
 SELECT * FROM results WHERE [RN] = 1; 

已更新

我尝试注入两个ROW_NUMBER(),但我收到的是第10行和第25行,它们是某些特定ID的第一行。

 With results as 
     (
       i.*, 
       ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN], 
       ROW_NUMBER() OVER (ORDER BY I.ID) AS [R]
       FROM HolidayList AS I
       INNER JOIN (
          SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
       )
       AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
     )
     SELECT * FROM results WHERE [RN] = 1 AND BETWEEN [R]>10 AND [R]<25

我真正想要的是select a specific range from all the first row for each id

FINAL

感谢McGlothlin,最后我解决了。我需要的是嵌套的CTE

With First_CTE as 
         (
           i.*, 
           ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY I.ID DESC) AS [RN]
           FROM HolidayList AS I
           INNER JOIN (
              SELECT ID, MIN(CreateDate) FROM HolidayList GROUP BY ID
           )
           AS j ON i.ID = j.ID AND i.CreateDate = j.CreateDate
         ),
         results AS 
          (
            SELECT k.*,  
            ROW_NUMBER() OVER (ORDER BY k.ID DESC) AS [R] 
            FROM First_CTE AS k WHERE k.[RN] = 1
          )
          SELECT * FROM results WHERE [R]>10 AND [R]<25

1 个答案:

答案 0 :(得分:2)

问题出在这一行:

package main

import (
    "log"
    "net/http"
    "github.com/rs/cors"
    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "myApp/src/controllers"
)

func main() {
    ac := new(controllers.AccountController)

    router := mux.NewRouter()
    router.HandleFunc("/signup", ac.SignUp).Methods("POST")
    router.HandleFunc("/signin", ac.SignIn).Methods("POST")

    c := cors.New(cors.Options{
    AllowedOrigins: []string{"http://localhost:8000"},
    AllowCredentials: true,
    })

    handler := c.Handler(router)

    log.Fatal(http.ListenAndServe(":3000", handler )
}

我认为你的意思是:

ROW_NUMBER() OVER I.ID AS [R]

这假设您要在CTE中返回的每一行上给它一个行计数。 ROW_NUMBER() OVER (ORDER BY I.ID) AS [R] 函数需要指定ROW_NUMBER(),如果您使用的ORDER BY函数可以在没有{OVER的情况下使用,则SUM子句仍然需要括号1}}。

编辑:根据您的评论,听起来您正在寻找的是ORDER BY。在这种情况下,您将删除第二个OFFSET并包含以下内容:

ROW_NUMBER

这将返回第11到第25行,按ORDER BY ID OFFSET 10 ROWS FETCH FIRST 15 ROWS ONLY 排序。

由于ID语法在SQL Server 2008中不起作用,因此您应该执行以下操作作为最终结果:

OFFSET