三表差异查询

时间:2012-02-24 14:14:20

标签: sql-server

我有3张桌子:NamesToDoTasksDone。他们的列结构如下:

'Names' table:
    Name (nvarchar)
    Status (nvarchar)

'ToDo' table:
    Task (nvarchar)
    Date (smalldatetime)
    Name (nvarchar)

'TasksDone' table:
    TaskStatus (nvarchar)
    Date (smalldatetime)
    Name (nvarchar)
'Names' table:
Name    | Status
John    | Available 
Ryan    | Available 
Sean    | NotAvailable

'ToDo' table:
Task      | Date       | Name
Washing   | 01.01.2012 | John   
Cleaning  | 03.01.2012 | Ryan
Washing   | 04.01.2012 | Sean   

'TasksDone' table:
TaskStatus| Date       | Name
Done      | 01.01.2012 | John   
Done      | 02.01.2012 | Ryan
NotDone   | 02.01.2012 | Sean   

我想从Name表中获取所有Names Status='Available'表格ToDoTasksDone和{{1}}表格中找不到({1}}日期)。

1 个答案:

答案 0 :(得分:1)

试试这个(YOUR_DATE是您的日期,必须更换)

SELECT
    n.Name
FROM Names n
LEFT OUTER JOIN ToDo t
    ON t.Name = n.Name
    AND t.Date = YOUR_DATE
LEFT OUTER JOIN TasksDone td
    ON td.Name = n.Name
    AND td.Date = YOUR_DATE
WHERE
    n.Status = 'Available'
    AND t.Name IS NULL
    AND td.Name IS NULL