显示过去31天(一个月)未借出的DVD数据

时间:2016-04-12 21:08:30

标签: sql asp.net sql-server visual-studio

我想显示商店中所有DVD标题的列表,其中在Visual Studio Asp的GridView中过去31天(DateOut >= Current_date – 31)没有借出标题副本。我在下面有一个SQL查询,但我不知道在 WHERE 子句中放入什么:

SELECT DVDTitle.DVDNumber, DVDTitle.DVDTitle
  FROM DVDTitle
  INNER JOIN DVDCopy
    ON DVDTitle.DVDNumber = DVDCopy.DVDNumber
  INNER JOIN Loan
    ON DVDCopy.CopyNumber = Loan.CopyNumber
  WHERE <what goes here?>
  ORDER BY DVDTitle.DVDNumber;

2 个答案:

答案 0 :(得分:0)

我想使用NOT EXISTS来进行此类查询:

SELECT t.*
FROM DVDTitle t
WHERE NOT EXISTS (SELECT 1
                  FROM DVDCopy c JOIN
                       DVDLoan l
                       ON c.CopyNumber = l.CopyNumber
                  WHERE t.DVDNumber = c.DVDNumber AND
                        l.DateOut >= DATEADD(day, -31, GETDATE())
                 );

在任何情况下,最终条件中的日期算术在数据库之间变化很大。这是(相当于任意)使用SQL Server日期函数。 ANSI标准更像l.DateOut >= CURRENT_TIMESTAMP - INTERVAL '31 DAY'

答案 1 :(得分:0)

使用DATEDIFF()和GETDATE()

DATEDIFF:https://msdn.microsoft.com/en-us/library/ms189794.aspx

GETDATE:https://msdn.microsoft.com/en-us/library/ms188383.aspx

WHERE DATEDIFF(day, Loan.DateOut, GETDATE()) >= 31