MSACCESS - 此子查询最多可返回一条记录

时间:2017-06-01 07:00:47

标签: sql ms-access

请帮我修复这个SQL查询:

SELECT DISTINCT [ClassSessions].Shortcode
    ,[CertIV_BC_A].ID
    ,[CertIV_BC_A].Units
    ,[CertIV_BC_A].AT
    ,Format((
            SELECT DATE
            FROM ClassSessions
            WHERE [ClassSessions].[Code] = [CertIV_BC_A].[SessionStart]
                AND ([ClassSessions].[OccurenceID] = '34849')
            ), 'dd/mm/yy') AS StartDate
    ,[CertIV_BC_A].SessionStart
    ,[CertIV_BC_A].SessionEnd
FROM CertIV_BC_A
    ,ClassSessions
WHERE (([ClassSessions].[OccurenceID] = '34849'))
ORDER BY [CertIV_BC_A].ID;

这是2个数据库:
CertIV_BC_A Cert IV_BC_A_Database


ClassSessions ClassSessions Database

当ClassSessions数据库中只有1个OccurenceID时,查询工作。但是,当ClassSessions中有超过1个OccurenceID时,我会收到错误。

这是查询的结果 模块ID AT StartDate EndDate

  • 列表项
  • 模块1 1 AT1 5/10/2017 31/05/2017
  • 模块1 2 AT2 24/05/2017 26/06/2017
  • 模块1 3 AT3
  • 模块1 4 AT4
  • 模块1 5 AT5
  • 模块2 6 AT1 28/06/2017 28/08/2017
  • 模块2 7 AT2 28/06/2017 8/07/2017

如果我需要提供更多详细信息,请与我们联系。非常感谢你

2 个答案:

答案 0 :(得分:0)

从子查询中选择前1或最大日期

SELECT DISTINCT
  [ClassSessions].Shortcode,
  [CertIV_BC_A].ID,
  [CertIV_BC_A].Units,
  [CertIV_BC_A].AT,
  Format(
   (SELECT
    MAX(Date)
    FROM ClassSessions
    WHERE [ClassSessions].

   [Code] = [CertIV_BC_A].[SessionStart]
    AND ([ClassSessions].[OccurenceID] = '34849')), 'dd/mm/yy') AS StartDate,
  [CertIV_BC_A].SessionStart,
  [CertIV_BC_A].SessionEnd

FROM CertIV_BC_A,
     ClassSessions
WHERE (([ClassSessions].[OccurenceID] = '34849'))

ORDER BY [CertIV_BC_A].ID;

答案 1 :(得分:0)

我将Format放在子查询中。

,(
    SELECT Format(DATE, 'dd/mm/yy')
    FROM ClassSessions
    WHERE [ClassSessions].[Code] = [CertIV_BC_A].[SessionStart]
        AND ([ClassSessions].[OccurenceID] = '34849')
  ) AS StartDate