某个日期的SQL查询详细信息

时间:2013-03-25 07:26:19

标签: sql date

我有以下数据库:

create table Hotel  (
   HNo char(4),
   Name varchar(20)   not null,
   Address varchar(50),
   Constraint PK_Hotel Primary Key (HNo))
)


create table Room  (
   RNo char(4),
   HNo char(4),
   Type char(6) not null,
   Price decimal (7,2),
   Constraint PK_Room Primary Key (HNo, RNo),
   Constraint FK_Room Foreign Key (HNo)
   references Hotel (HNo)
)


create table Guest  (
   GNo char(4),
   Name varchar(20) not null,
   Address varchar(50),
   Constraint PK_Guest Primary Key (GNo)

)


create table Booking   (
   HNo char(4),
   GNo char(4),
   DateFrom date,
   DateTo date,
   RNo char(4),
   Constraint PK_Booking Primary Key (HNo, GNo, DateFrom),
   Constraint FK_Booking Foreign Key (GNo)
   references Guest (GNo),
   Constraint FK_Booking_room Foreign Key (HNo, RNo)
   references Room (HNo, RNo),
   Constraint FK_Booking_hotel Foreign Key (HNo)
   references Hotel (HNo)
)

我正在努力的是使用dateto=> <=datefrom并让它发挥作用。

1997年3月26日,我需要列出所有酒店所有房间的详细信息,包括入住客房的所有客人的姓名。加入表等我不是太糟糕,但我不确定如何在指定日期整体做到这一点?有什么想法吗?

2 个答案:

答案 0 :(得分:1)

SELECT
  h.Name,
  h.Address,
  r.RNo,
  r.HNo,
  r.Type,
  r.Price,
  G.Name,
  G.Address,
  ...
FROM Hotel         AS h
INNER JOIN Room    AS r  ON h.HNo = r.HNo
INNER JOIN Guest   AS g  ON r.RNo = g.RNo
INNER JOIN Booking AS b  ON b.GNo = g.GNo
                        AND b.HNo = h.HNo
WHERE b.DateFrom <= @DateFrom
  AND b.DateTo   => @DateTo;

答案 1 :(得分:1)

  SELECT b.datefrom, b.dateto, h.name AS hotelname
         , b.rno
         , r.type
         , g.name AS guestname
    FROM booking b
    JOIN hotel h ON b.hno = h.hno
    JOIN guest g ON g.gno = b.gno
    JOIN room r ON b.rno = r.rno
   WHERE @yourDate BETWEEN b.datefrom AND b.dateto

编辑:

将最后一行中的@yourDate替换为DBMS支持的合适表达式。

例如,在Oracle中,有一个函数TO_DATE将给定的字符串转换为日期,如TO_DATE('26-MAR-1997') BETWEEN b.datefrom AND b.dateto。在SQL Server中有CAST函数。

相关问题