如何选择SQL数据库中的2个最新条目

时间:2016-01-28 10:10:30

标签: sql sql-server greatest-n-per-group

我是sql的新手,我对这个主题还没有太多的了解,我有一个问题。我试图使用此查询从我的数据库表中选择数据:

SELECT 
Distinct
    UPPER(M.name) AS 'Member Name',
    M.memberID AS 'Member ID',
    (b.bookTitle + ' / ' + a.firstName + ' ' + a.lastName) AS 'Title',
    l.barCode AS 'barcode',
    (CONVERT(VARCHAR(8), lr.dueDate, 5) + ' Renewed ' + CONVERT(VARCHAR(1), 
    (SELECT COUNT(lr.LoanID)
     FROM Loan l, LoanRenewal lr
     WHERE lr.LoanID = l.loanID
       AND l.memberID = 's002')) + ' times') AS 'Status',
    bc.callNumber AS 'Call Number'
FROM 
    Book b,
    Author a,
    BookAuthor ba,
    bookCopy bc,
    Member M,
    MemberType mt,
    Loan l,
    LoanRenewal lr,
    PublishWork pw
WHERE 
    M.memberID = 's002'
    AND M.memberID = l.memberID
    AND l.loanID = lr.LoanID
    AND l.barCode = bc.barCode
    AND bc.ISBN = pw.ISBN
    AND pw.BookId = b.BookID
    AND ba.BookID = b.BookID
    AND b.Main_AuthorID = a.authorID

当我运行它时,它返回的结果是

Member Name | Member ID | Title                        | barcode | Status                  | Call Number |
LIM HAI MEI | S002      | Developing an App / Ben Grimm| 1234567 | 20-02-16 Renewed 4 times|TK5105.887 Kar|
LIM HAI MEI | S002      | Java 101 / Yee Chak Thong    | abcdefg | 20-02-16 Renewed 4 times|TK5105.886 Kar|
LIM HAI MEI | S002      | Java 101 / Yee Chak Thong    | abcdefg | 25-02-16 Renewed 4 times|TK5105.886 Kar|
LIM HAI MEI | S002      | Java 101 / Yee Chak Thong    | abcdefg | 28-02-16 Renewed 4 times|TK5105.886 Kar|

但是我希望它返回的是因为我只想要最近的记录以及如何动态隔离数据

 Member Name | Member ID | Title                        | barcode | Status                  | Call Number |
LIM HAI MEI | S002      | Developing an App / Ben Grimm| 1234567 | 20-02-16 Renewed 1 times|TK5105.887 Kar|
LIM HAI MEI | S002      | Java 101 / Yee Chak Thong    | abcdefg | 28-02-16 Renewed 4 times|TK5105.886 Kar|

请帮助我,我找不到合适的动态代码而不是硬编码

2 个答案:

答案 0 :(得分:1)

这取决于是否有一个字段可以对新内容进行排名,我在上面的查询中无法看到。假设你有,你想要的是使用像这样的ROW_NUMBER函数 -

SELECT
    <FieldList>
FROM
    (SELECT
        ROW_NUMBER() OVER (ORDER BY Newness DESC) Ix,
        <FieldList>
    FROM
        <Tables>) x
WHERE
    Ix <=2

答案 1 :(得分:1)

您需要使用Group By&amp;列状态的聚合(最大值是最近的一个)

    SELECT [MEMBER NAME],[MEMBER ID],[TITLE],[BARCODE],MAX(STATUS),[CALL NUMBER]
    FROM (

    --YOUR CODE MENTIONED IN QUESTION

    )AS A
    GROUP BY [MEMBER NAME],[MEMBER ID],[TITLE],[BARCODE],[CALL NUMBER]