显示访问中没有数据的行

时间:2016-08-08 12:37:55

标签: sql ms-access inner-join

我有以下查询:

SELECT PersonTotalHours.MA, PersonTotalHours.Year, PersonTotalHours.CalendarWeek,
PersonTotalHours.Hours, Person.Name, Person.Lastname 
FROM PersonTotalHours
INNER JOIN Person
ON PersonTotalHours.MA = Person.MA;

结果如下表所示:

  MA       Year    CalendarWeek    Hours    Name    Lastname
  aA       2000         5           53      aa        AA
  aA       2000         44          175     aa        AA
  ...      ...         ...          ...
  aA       2001         4           226     aa        AA
  aA       2001         12          87      aa        AA
  ...      ...         ...          ...
  bB       2000         1           189     bb        BB
  bB       2000         35          65      bb        BB
  ...      ...         ...          ...

如您所见,某些日历周没有数据。对于现在不存在的那些日历周(1到53)和小时= 0,我有什么方法可以获得一行吗?

修改 我通过向表中添加缺少的行来暂时解决这个问题。使用报表打开时调用的函数。仍在寻找一个非愚蠢的解决方案。

2 个答案:

答案 0 :(得分:4)

创建帮助表Calendar,存储所有可能的值。 RIGHT JOIN它:

SELECT pth.MA, pth.Year, pth.CalendarWeek,
pth.Hours, p.Name, p.Lastname 
FROM PersonTotalHours pth
INNER JOIN Person p
    ON pth.MA = p.MA
RIGHT JOIN Calendar c
    ON pth.Year = c.Year AND pth.CalendarWeek = c.CalendarWeek

(使用表别名来节省一些打字。)

编辑: MS Access查询尝试,版本1:

SELECT pth.MA, pth.Year, pth.CalendarWeek,
pth.Hours, p.Name, p.Lastname 
FROM (PersonTotalHours pth
INNER JOIN Person p
    ON pth.MA = p.MA)
RIGHT JOIN Calendar c
    ON pth.Year = c.Year AND pth.CalendarWeek = c.CalendarWeek

编辑: MS Access查询尝试,版本2:

SELECT pth.MA, pth.Year, pth.CalendarWeek,
pth.Hours, p.Name, p.Lastname 
FROM calendar
    left join (PersonTotalHours pth
               INNER JOIN Person p ON pth.MA = p.MA)
    ON pth.Year = c.Year AND pth.CalendarWeek = c.CalendarWeek

答案 1 :(得分:0)

请检查此查询。

select PersonTotalHours.MA,PersonTotalHours.YEAR,b.CalendarWeek, PersonTotalHours.Hours, '' Name, '' LastName from PersonTotalHours
right join (
select '' MA, 0 Year, no CalendarWeek, 0 Hours, '' Name, '' Lastname from (
select row_number() over(order by object_id) no from sys.all_objects
) a where no <= 53) b on b.CalendarWeek = Table_1.CalendarWeek

我没有加入人员表。