加入多个子查询

时间:2018-12-08 04:02:17

标签: sql ms-access

我正在尝试使用多个选择查询将同一数据上的多个WHERE子句合并为1个查询。当我加入1个子查询时,它起作用了,但是当我尝试加入第二个子查询时,出现语法错误,我很难解决。任何帮助将不胜感激!

SELECT [CONSULTATION].Theatre
  ,[CONSULTATION].[Order Type]
  ,[CONSULTATION].[Service Type]
  ,[CONSULTATION].[ORDERS]
  ,[CONSULTATION].[CONSULTATION DAYS]
  ,[DESIGN].[DESIGN DAYS]
FROM (
  SELECT [Order Metrics].Theatre
    ,[Order Metrics].[Order Type]
    ,[Order Metrics].[Service Type]
    ,Count([Order Metrics].[Order ID]) AS ORDERS
    ,ROUND(AVG(([Order Metrics].HOURS) / 24), 1) AS [CONSULTATION DAYS]
  FROM [Order Metrics]
  WHERE (
      (([Order Metrics].[Order Status]) = "closed")
      AND ((DateDiff("d", [Order Metrics] ! [Date Created], Now())) < 366)
      AND (
        (
          [ORDER METRICS] ! FROM
          ) = "CONSULTATION"
        )
      )
  GROUP BY [Order Metrics].Theatre
    ,[Order Metrics].[Order Type]
    ,[Order Metrics].[Service Type]
  HAVING LEN([ORDER METRICS].[THEATRE]) > 1
  ) AS CONSULTATION
INNER JOIN (
  SELECT [Order Metrics].Theatre
    ,[Order Metrics].[Order Type]
    ,[Order Metrics].[Service Type]
    ,Count([Order Metrics].[Order ID]) AS ORDERS
    ,ROUND(AVG(([Order Metrics].HOURS) / 24), 1) AS [DESIGN DAYS]
  FROM [Order Metrics]
  WHERE (
      (([Order Metrics].[Order Status]) = "closed")
      AND ((DateDiff("d", [Order Metrics] ! [Date Created], Now())) < 366)
      AND (
        (
          [ORDER METRICS] ! FROM
          ) = "DESIGN"
        )
      )
  GROUP BY [Order Metrics].Theatre
    ,[Order Metrics].[Order Type]
    ,[Order Metrics].[Service Type]
  HAVING LEN([ORDER METRICS].[THEATRE]) > 1
  ) AS DESIGN ON ([CONSULTATION].Theatre = [DESIGN].THEATRE)
  AND ([CONSULTATION].[Order Type] = [DESIGN].[ORDER TYPE])
  AND ([CONSULTATION].[Service Type] = [DESIGN].[SERVICE TYPE])
INNER JOIN (
  SELECT [Order Metrics].Theatre
    ,[Order Metrics].[Order Type]
    ,[Order Metrics].[Service Type]
    ,Count([Order Metrics].[Order ID]) AS ORDERS
    ,ROUND(AVG(([Order Metrics].HOURS) / 24), 1) AS [QUOTE REQUEST DAYS]
  FROM [Order Metrics]
  WHERE (
      (([Order Metrics].[Order Status]) = "closed")
      AND ((DateDiff("d", [Order Metrics] ! [Date Created], Now())) < 366)
      AND (
        (
          [ORDER METRICS] ! FROM
          ) = "QUOTE REQUEST"
        )
      )
  GROUP BY [Order Metrics].Theatre
    ,[Order Metrics].[Order Type]
    ,[Order Metrics].[Service Type]
  HAVING LEN([ORDER METRICS].[THEATRE]) > 1
  ) AS [QUOTE REQUEST] ON ([CONSULTATION].Theatre = [QUOTE REQUEST].THEATRE)
  AND ([CONSULTATION].[Order Type] = [QUOTE REQUEST].[ORDER TYPE])
  AND ([CONSULTATION].[Service Type] = [QUOTE REQUEST].[SERVICE TYPE]);

1 个答案:

答案 0 :(得分:0)

您是否考虑过分别保存每个查询,检查它们是否具有相同数据类型的相同列数,然后将它们与联合查询一起拉到一起?我发现这更容易维护...