如何仅显示日期可用的女仆? SQL服务器

时间:2019-07-01 09:03:51

标签: sql-server

我有一个女佣表,其中存储了女佣详细信息,还有一个约会表,该表存储了约会详细信息,例如将每个约会分配给哪个女仆,因此约会表中保存了女仆ID。如何仅显示尚未分配给任何工作的女佣(可用女佣)和女佣可用的日期?

餐桌女仆

enter image description here

表约会

enter image description here

我做了什么。

SELECT Maid_ID FROM Maid
EXCEPT
SELECT WO_MaidName FROM Appointments

考虑到2019-06-03的用户输入,我想要这个结果:

Maid_ID    Available Date
--------------------------
   2        2019-06-03
   3        2019-06-03
   5        2019-06-03

4 个答案:

答案 0 :(得分:1)

您尝试过吗?

SELECT Maid_ID 
FROM Maid LEFT JOIN Appointments
    ON Maid.Maid_ID = Appointments.WO_MaidName
WHERE Appointments.WO_MaidName IS NULL

此查询返回Maid表中的所有行,而Appointments表中未关联任何行。

SELECT Maid_ID
FROM Maid
WHERE Maid_ID NOT IN (
    SELECT WO_MaidName
    FROM Appointments
    WHERE Appointment_DateTime BETWEEN '20190603' AND '20190604')

第二个查询返回所有Maid行,其中where子句中的日期之间没有约会。

答案 1 :(得分:0)

也许这不是经过优化的,但是可以。

CREATE TABLE #TEMP 
    (
        Maid_Id INT,
        AppointmentDateTime DATETIME
    )

DECLARE db_cursor CURSOR FOR SELECT distinct Appointment.AppointmentDateTime FROM Appointment; 
DECLARE @date datetime;
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @date;
WHILE @@FETCH_STATUS = 0  
BEGIN  
        INSERT INTO #TEMP (Maid_Id, AppointmentDateTime)
        SELECT M.Maid_Id, @date FROM Maid M
        WHERE M.Maid_Id NOT IN (
            SELECT a.Maid_Id FROM Appointment a
            WHERE A.AppointmentDateTime = @date
        )

       FETCH NEXT FROM db_cursor INTO @date;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

SELECT T.Maid_Id, M.Maid_Name, T.AppointmentDateTime FROM #TEMP T
INNER JOIN Maid M ON T.Maid_Id = M.Maid_Id
ORDER BY AppointmentDateTime

DROP TABLE #TEMP

enter image description here

答案 2 :(得分:0)

另一种解决方案是使用一个特定的日期,并在每个日期调用您想要的日期。 首先,像这样在Table-valued Function中添加一个SqlServer

CREATE FUNCTION [dbo].[MyFunction]
(   
    @date datetime
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT M.Maid_Id FROM Maid M
            WHERE M.Maid_Id NOT IN (
                SELECT a.Maid_Id FROM Appointment a
                WHERE A.AppointmentDateTime = @date
            )
)

然后这样称呼:

DECLARE @Date DATETIME = '2019-05-15 00:00:00.000'; // Put the date you want
SELECT m.Maid_Id, m.Maid_Name, @Date FROM Maid M
INNER JOIN [dbo].[MyFunction](@Date) F ON M.Maid_Id = F.Maid_Id

enter image description here

答案 3 :(得分:0)

最后,请尝试以下操作:

Sub writeToTextFile()
    Dim i As Long
    Open ThisWorkbook.Path & "\newFile.txt" For Output As #1

    Print #1, "This could be the first line"
    Print #1, "this the second"

    For i = 3 To 10
        Print #1, "this is the " & i & ". line"
    Next

    Close #1
End Sub

结果是这样的:

enter image description here