获取SQL中WHERE条件的最后一条记录

发布于 2024-11-28 05:06:00 字数 360 浏览 1 评论 0原文

我有 loanTable 包含两个字段 loan_idstatus

loan_id status
==============
1       0
2       9
1       6
5       3
4       5
1       4  <-- How do I select this??
4       6

在这种情况下,我需要显示 Status 的最后一个 Status code>loan_id 1 即 status 4. 请帮助我完成此查询。

i have loanTable that contain two field loan_id and status

loan_id status
==============
1       0
2       9
1       6
5       3
4       5
1       4  <-- How do I select this??
4       6

In this Situation i need to show the last Status of loan_id 1 i.e is status 4. Can please help me in this query.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

苍景流年 2024-12-05 05:06:00

由于 ID 1 的“最后”行既不是最小值也不是最大值,因此您生活在一种轻度混乱的状态中。表中的行没有顺序。因此,您应该提供另一列,可能是插入每行时的日期/时间,以提供数据的排序。另一个选项可以是一个单独的、自动递增的列,用于记录插入行的顺序。然后就可以编写查询了。

如果额外的列名为 status_id,那么您可以这样写:(

SELECT L1.*
  FROM LoanTable AS L1
 WHERE L1.Status_ID = (SELECT MAX(Status_ID)
                         FROM LoanTable AS L2
                        WHERE L2.Loan_ID = 1);

表别名 L1 和 L2 可以省略,而不会让 DBMS 或有经验的 SQL 程序员感到困惑。)

就目前情况而言,没有可靠的方法知道哪一行是最后一行,因此您的查询无法回答。

Since the 'last' row for ID 1 is neither the minimum nor the maximum, you are living in a state of mild confusion. Rows in a table have no order. So, you should be providing another column, possibly the date/time when each row is inserted, to provide the sequencing of the data. Another option could be a separate, automatically incremented column which records the sequence in which the rows are inserted. Then the query can be written.

If the extra column is called status_id, then you could write:

SELECT L1.*
  FROM LoanTable AS L1
 WHERE L1.Status_ID = (SELECT MAX(Status_ID)
                         FROM LoanTable AS L2
                        WHERE L2.Loan_ID = 1);

(The table aliases L1 and L2 could be omitted without confusing the DBMS or experienced SQL programmers.)

As it stands, there is no reliable way of knowing which is the last row, so your query is unanswerable.

小兔几 2024-12-05 05:06:00

您的表是否有主 ID 或时间戳?如果不是,那么您想要的就不可能实现。

如果是的话:

    SELECT TOP 1 status
    FROM loanTable
    WHERE loan_id = 1
    ORDER BY primaryId DESC
    -- or
    -- ORDER BY yourTimestamp DESC

Does your table happen to have a primary id or a timestamp? If not then what you want is not really possible.

If yes then:

    SELECT TOP 1 status
    FROM loanTable
    WHERE loan_id = 1
    ORDER BY primaryId DESC
    -- or
    -- ORDER BY yourTimestamp DESC
独自唱情﹋歌 2024-12-05 05:06:00

我假设“最后状态”是指最近插入的记录? AFAIK 除非您将时间戳添加到存储添加记录时的日期和时间的表中,否则无法进行此类查询。 RDBMS 不保留记录的任何内部顺序。

I assume that with "last status" you mean the record that was inserted most recently? AFAIK there is no way to make such a query unless you add timestamp into your table where you store the date and time when the record was added. RDBMS don't keep any internal order of the records.

牛↙奶布丁 2024-12-05 05:06:00

但如果最后=最后插入,这对于当前模式是不可能的,直到添加PK:

select top 1 status, loan_id
from loanTable
where loan_id = 1
order by id desc -- PK

But if last = last inserted, that's not possible for current schema, until a PK addition:

select top 1 status, loan_id
from loanTable
where loan_id = 1
order by id desc -- PK
梨涡 2024-12-05 05:06:00

使用数据读取器。当它退出 while 循环时,它将位于最后一行。正如其他发帖者所说,除非您对查询进行排序,否则行顺序可能会改变。即使表上有聚集索引,它也可能不会按该顺序返回行(不对聚集索引进行排序)。

    SqlDataReader rdr = SQLcmd.ExecuteReader();
    while (rdr.Read())
    {
    }
    string lastVal = rdr[0].ToString()
    rdr.Close();

您还可以使用 ROW_NUMBER() 但这需要排序,并且不能直接在Where 中使用ROW_NUMBER()。但您可以通过创建派生表来欺骗它。上面的 rdr 解决方案更快。

Use a data reader. When it exits the while loop it will be on the last row. As the other posters stated unless you put a sort on the query, the row order could change. Even if there is a clustered index on the table it might not return the rows in that order (without a sort on the clustered index).

    SqlDataReader rdr = SQLcmd.ExecuteReader();
    while (rdr.Read())
    {
    }
    string lastVal = rdr[0].ToString()
    rdr.Close();

You could also use a ROW_NUMBER() but that requires a sort and you cannot use ROW_NUMBER() directly in the Where. But you can fool it by creating a derived table. The rdr solution above is faster.

街道布景 2024-12-05 05:06:00

在oracle数据库中这非常简单。

select * from (select * from LoanTable order by rownum desc) 其中 rownum=1

In oracle database this is very simple.

select * from (select * from loanTable order by rownum desc) where rownum=1

猫腻 2024-12-05 05:06:00

您好,如果这个问题还没有解决。
要从表中获取任何字段的最后一条记录,最简单的方法是向每个记录添加一个 ID(例如 pID)。另外,如果您希望在表中记录每个“名称”的最后一条记录,请运行简单的查询。

SELECT Name, MAX(pID) as LastID
INTO [TableName]
FROM [YourTableName]
GROUP BY [Name]/[Any other field you would like your last records to appear by]    

您现在应该有一个表,其中一列中包含名称以及该名称的最后一个可用 ID。
现在,您可以使用联接从主表中获取其他详细信息,假设这是某个价格或日期,然后运行以下命令:

SELECT a.*,b.Price/b.date/b.[Whatever other field you want]
FROM [TableName] a LEFT JOIN [YourTableName] 
ON a.Name = b.Name and a.LastID = b.pID

然后,这应该为您提供每个名称的最后一条记录,对于第一条记录,运行与上面相同的查询只需将上面的 Max 替换为 Min 即可。

这应该很容易理解并且运行得更快

Hi if this has not been solved yet.
To get the last record for any field from a table the easiest way would be to add an ID to each record say pID. Also say that in your table you would like to hhet the last record for each 'Name', run the simple query

SELECT Name, MAX(pID) as LastID
INTO [TableName]
FROM [YourTableName]
GROUP BY [Name]/[Any other field you would like your last records to appear by]    

You should now have a table containing the Names in one column and the last available ID for that Name.
Now you can use a join to get the other details from your primary table, say this is some price or date then run the following:

SELECT a.*,b.Price/b.date/b.[Whatever other field you want]
FROM [TableName] a LEFT JOIN [YourTableName] 
ON a.Name = b.Name and a.LastID = b.pID

This should then give you the last records for each Name, for the first record run the same queries as above just replace the Max by Min above.

This should be easy to follow and should run quicker as well

幸福不弃 2024-12-05 05:06:00

如果您没有任何标识列,则可以使用它来获取插入顺序。你总是可以这样做。但它很老套,而且不太漂亮。

select
t.row1,
t.row2,
ROW_NUMBER() OVER (ORDER BY t.[count]) AS rownum from (
select 
    tab.row1,
    tab.row2,
    1 as [count] 
from table tab) t

所以基本上你会得到“自然顺序”(如果你可以这样称呼它),并添加一些包含所有相同数据的列。这可用于按“自然顺序”排序,使您有机会在下一个查询中放置行号列。

就个人而言,如果您使用的系统没有时间戳/身份列,并且当前用户正在使用“自然顺序”,我会快速添加一列并使用此查询来创建某种时间戳/增量钥匙。而不是冒着让某些自动化机制改变“自然顺序”、破坏所需数据的风险。

If you don't have any identifying columns you could use to get the insert order. You can always do it like this. But it's hacky, and not very pretty.

select
t.row1,
t.row2,
ROW_NUMBER() OVER (ORDER BY t.[count]) AS rownum from (
select 
    tab.row1,
    tab.row2,
    1 as [count] 
from table tab) t

So basically you get the 'natural order' if you can call it that, and add some column with all the same data. This can be used to sort by the 'natural order', giving you an opportunity to place a row number column on the next query.

Personally, if the system you are using hasn't got a time stamp/identity column, and the current users are using the 'natural order', I would quickly add a column and use this query to create some sort of time stamp/incremental key. Rather than risking having some automation mechanism change the 'natural order', breaking the data needed.

最舍不得你 2024-12-05 05:06:00

我认为这段代码可以帮助你:

WITH cte_Loans
AS
(
SELECT   LoanID
        ,[Status]
        ,ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RN
FROM    LoanTable
)

SELECT   LoanID
        ,[Status]
FROM    LoanTable L1
WHERE   RN = (  SELECT max(RN)
                FROM LoanTable L2
                WHERE L2.LoanID = L1.LoanID)

I think this code may help you:

WITH cte_Loans
AS
(
SELECT   LoanID
        ,[Status]
        ,ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RN
FROM    LoanTable
)

SELECT   LoanID
        ,[Status]
FROM    LoanTable L1
WHERE   RN = (  SELECT max(RN)
                FROM LoanTable L2
                WHERE L2.LoanID = L1.LoanID)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文