简体   繁体   English

从数据库c sharp中选择第5个条目

[英]Select 5th entry from database c sharp

Im trying to sort a database table then select the 5th entry. 我试图对数据库表进行排序,然后选择第5个条目。

I have got the code below but this dosnt seem to give me the correct value Can anyone help please? 我有下面的代码,但这个dosnt似乎给了我正确的价值任何人都可以帮忙吗?

OleDbCommand com12 = new OleDbCommand(@"SELECT TOP 5 [Flight_Date] 
                                        FROM Flights 
                                        WHERE [Claimed_By_ID] = ? 
                                         AND [Flight_Date] <= ?
                                         AND [Flight_Date] >= ? 
                                        ORDER BY [Flight_Date] DESC", Program.DB_CONNECTION);
com12.Parameters.Add(new OleDbParameter("", p.ID));
com12.Parameters.Add(new OleDbParameter("", DateTime.Today));
com12.Parameters.Add(new OleDbParameter("", DateTime.Today.AddMonths(-6)));
OleDbDataReader dr12 = com12.ExecuteReader();

You can wrap your query in another query: 您可以将查询包装在另一个查询中:

SELECT MIN([Flight_Date]) AS [Flight_Date_5]
FROM (SELECT TOP 5 [Flight_Date] 
      FROM Flights 
      WHERE [Claimed_By_ID] = ? 
       AND [Flight_Date] <= ?
       AND [Flight_Date] >= ? 
      ORDER BY [Flight_Date] DESC) AS [Top5]

This will just return the 5th highest entry. 这将返回第五高的条目。 If there are fewer than 5 total entries, it will return the lowest of them. 如果总条目少于5个,则返回最低条目。

Use a DataTable , fill it with your reader then get the fifth record with LINQ : 使用DataTable ,用读者填写,然后使用LINQ获取第五条记录:

DataTable dt = new DataTable();
dt.Load(com12.ExecuteReader());
var fifthRow = dt.AsEnumerable().Skip(4).First();

UPDATE: 更新:

Sorry this is SQL Server ONLY. 对不起,这只是SQL Server。 It won't work for MYSQL. 它不适用于MYSQL。

Use a CTE is another correct way: 使用CTE是另一种正确的方法:


WITH AllData AS
(
SELECT TOP 5 ROW_NUMBER() OVER (order by [Flight_Date] DESC) as RowNumber
      FROM Flights 
      WHERE [Claimed_By_ID] = ? 
       AND [Flight_Date] = ? 
)
SELECT * FROM AllData WHERE RowNumber = 5

If there aren't 5 rows, it will return nothing. 如果没有5行,则不返回任何内容。

MySQL doesn't have TOP . MySQL没有TOP Use LIMIT ... 使用LIMIT ......

SELECT [Flight_Date] 
    FROM Flights 
    WHERE [Claimed_By_ID] = ? 
     AND [Flight_Date] <= ?
     AND [Flight_Date] >= ? 
    ORDER BY [Flight_Date] DESC
    LIMIT 4, 1

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

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