简体   繁体   English

如何在SQL查询中使用当前日期格式

[英]How to use the current date format in a SQL Query

I am trying to do a query that calculates the days of past due library books in days. 我正在尝试执行一个查询,以天为单位计算过期图书馆图书的天数。 I also want to display the Patron's Last Name ( the person who borrowed the book), Book Title, the Due Date of the book. 我还想显示赞助人的姓氏(借书的人),书名,书的到期日。
I ran a simple query to understand what I am looking for. 我运行了一个简单的查询,以了解我在寻找什么。 The code I ran is as follows: 我运行的代码如下:

    SELECT PATRON.PAT_LNAME, BOOK.BOOK_TITLE, CHECKOUT.CHECK_DUE_DATE, 
           CHECKOUT.CHECK_IN_DATE 
           FROM CHECKOUT, BOOK, PATRON
           WHERE CHECKOUT.BOOK_NUM=BOOK.BOOK_NUM 
           AND CHECKOUT.PAT_ID= PATRON.PAT_ID
           AND CHECK_IN_DATE IS NULL 

I need to calculate the days that the book is overdue from the date that it was due. 我需要计算该书从到期之日算起的过期天数。 I want to use the current date to calculate the days that the book is overdue, although I am not sure how to do that. 我想用当前日期来计算这本书的过期日期,尽管我不确定该怎么做。 I know there is a SYSDATE function that gives the current date. 我知道有一个提供当前日期的SYSDATE函数。 I do not know how to use the SYSDATE function. 我不知道如何使用SYSDATE函数。

I think the marker for a past due book is that the current date is greater than the due date. 我认为过期书籍的标记是当前日期大于过期日期。 So you can just compare the due date against SYSDATE to determine which books are overdue and by how many days. 因此,您只需将到期日期与SYSDATE进行比较,即可确定哪些图书已过期,以及过期了多少天。

SELECT
    p.PAT_LNAME,
    b.BOOK_TITLE,
    c.CHECK_DUE_DATE, 
    c.CHECK_IN_DATE,
    SYSDATE - c.CHECK_DUE_DATE AS num_days_due
FROM CHECKOUT c
INNER JOIN BOOK b
    ON c.BOOK_NUM = b.BOOK_NUM
INNER JOIN PATRON p
    ON c.PAT_ID = p.PAT_ID
WHERE
    c.CHECK_IN_DATE IS NULL AND
    SYSDATE > c.CHECK_DUE_DATE;

In Oracle we can just subtract two dates to get the difference in days. 在Oracle中,我们可以减去两个日期来获得天数差异。 Note also that I replaced your implicit inner joins with explicit joins. 还要注意,我用显式联接替换了您的隐式内部联接。 This is the preferred way of writing a join query. 这是编写联接查询的首选方式。

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

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