找到缺少的日期 - vba Sql

时间:2015-05-25 14:08:34

标签: sql vba ms-access access-vba

我想找出哪个学生没有提交他的任务以及什么日期。我想检查每个学生当前与否。我不介意答案是在sql还是vba代码中。更多规格如下:

Task Table
-------------------------------
SubID  |ID | Task  | Date 
-------------------------------
1      |1  | Dance | 01-01-2014
2      |1  | Sing  | 02-01-2014
3      |1  | shout | 05-01-2014
4      |2  | try   | 02-01-2014
5      |3  | Okay  | 01-01-2014
6      |2  | random| 06-01-2014
8      |4  |Jumping| 01-01-2014
9      |4  | try   | 02-01-2014
10     |4  | Piano | 03-01-2014
11     |4  | try   | 04-01-2014
12     |4  | guitar| 05-01-2014
13     |4  | try   | 06-01-2014

Student table --the Date is in the dd-mm-yyyy format. - also it is a date/time datatype

ID | Name | Current
--------------------
1  | Ron  | YES
2  | sqlJ | YES
3  | jque | NO
4  | holy | YES
5  | htdoc| YES

期望的结果:

谁未在01-01-201406-01-2014

之间提交任务
ID | Date
---------------
1  | 03-01-2014
1  | 04-01-2014
1  | 06-01-2014
2  | 01-01-2014
2  | 03-01-2014
2  | 04-01-2014
2  | 05-01-2014
3  | 02-01-2014
3  | 03-01-2014
3  | 04-01-2014
3  | 05-01-2014
3  | 06-01-2014

我尝试过:

SELECT w.ID, w.Date, student.[first name], student.[last name], student.[id]
FROM tasktbl AS w 
     right join student 
           on w.id = student.[id];

//I was thinking of using a vba-for loop to iterate over the range of date and store it in an array spot every Id that doesn't have a date but it didn't work out quite well. 

任何帮助,从伪代码到sql代码到vba代码(基本上任何暗示我的任务)都将不胜感激

2 个答案:

答案 0 :(得分:1)

我使用了一个日历表,每个日期包含一行。将该表与学生交叉加入,并将日期范围限制为6个值,这给了我30行(6个日期乘以5个学生):

SELECT sub.*
FROM
    (
        SELECT c.the_date, s.ID
        FROM tblCalendar AS c, student AS s
        WHERE c.the_date Between #1/1/2014# And #1/6/2014#
    ) AS sub

然后我将其用作子查询,并将LEFT JOIN编辑为 tasktbl 。所以"右边的行#34;是空的,是那些学生在相关日期没有完成任务的地方。

SELECT sub.ID AS student_id, sub.the_date
FROM
    (
        SELECT c.the_date, s.ID
        FROM tblCalendar AS c, student AS s
        WHERE c.the_date Between #1/1/2014# And #1/6/2014#
    ) AS sub
    LEFT JOIN tasktbl AS t
    ON (sub.ID = t.ID) AND (sub.the_date = t.Date)
WHERE t.ID Is Null
ORDER BY sub.ID, sub.the_date;

答案 1 :(得分:0)

您应该可以在没有任何VBA的情况下执行此操作。

select s.id, t.date
from 
( --this will populate every possible date, for every student
    select distinct s.id 
    from students s
) s
cross join 
(
    select distinct t.date
    from taskTable t
) t
left join taskTable tt on s.id = tt.id and t.date = tt.date
where tt.date is null
--(optional) order by clause, if needed

基本上这是为每个可能的学生(来自""表)拉一个条目,为每个可能的日期(来自" t"表)拉一个条目进行交叉连接,生成一个结果集,其中包含每个可能学生的每个可能日期的行。通过将此连接返回到taskTable(其中taskTable的日期字段为空)将仅返回交叉连接表中的条目,这些条目具有与之关联的任务。

我还建议您重新考虑TaskTable的设计,而不是仅跟踪已完成的任务,跟踪所有任务并添加一个字段"已完成"如果任务已完成(是),则存储(否)。