Sql 使用子查询或参数时出错(但仅当同时使用两者时)

Sql 使用子查询或参数时出错(但仅当同时使用两者时),sql,excel,parameters,subquery,Sql,Excel,Parameters,Subquery,在Excel中使用SQL查询时,我遇到了一个奇怪的问题 有三个数据表: Table1 | Table2 | Table3 ------ | ------ | ------ Field1 Field2 | Field1 Field2 | Field1 Field2 Field3 ------ | ------ | -----

在Excel中使用SQL查询时,我遇到了一个奇怪的问题

有三个数据表:

Table1            |  Table2            |  Table3
------            |  ------            |  ------
Field1    Field2  |  Field1    Field2  |  Field1    Field2    Field3
------            |  ------            |  ------    
item1     value1  |  item1     date11  |  item1     amount11  date1
item2     value2  |  item1     date12  |  item1     amount12  date2
item3     value3  |  item1     date13  |  item2     amount21  date3
                  |  item2     date21  |  item2     amount22  date4
                  |  item2     date22  |  item3     amount31  date5
                  |  item2     date23  |  item3     amount32  date6
                  |  item3     date31  |  
                  |  item3     date32  |  
                  |  item3     date33  |  
我需要的是结果:

item1     value1     date11     amount11+amount12
item2     value2     date23     amount21+amount22
item3     value3     date33     amount31+amount32
其中第三列包含最近的日期so MAX(表2.Field2),第四列是所有金额的总和so sum(表3.Field2)。但是,我只需要在输入日期下方带有表3中日期的结果

这就是我想到的:

SELECT
      Table1.Field1, Table1.Field2, (
      SELECT
            MAX (Table2.Field2) FROM Table2 WHERE Table2.Field1=Table1.Field1
      ), SUM (Table3.Field2)
FROM
      Table1, Table3
WHERE
      Table1.Field1=Table3.Field1 AND Table3.Field3<=?
GROUP BY
      Table1.Field1
如果我执行以下任一操作,则错误已“解决”:

  • 删除子查询

  • 将日期直接放入查询中,即替换表3.Field3如果我理解正确,您可以使用联接和聚合来完成所有这些操作:

    select t1.field1, t1.field2, t2.date1, sum(t3.field2)
    from table1 t1 join
         (select t2.field1, max(date1) as date1
          from table2 t2
          group by t2.field1
         ) t2
         on t1.field1 = t2.field1 join
         table3 t3
         on t1.field1 = t3.field1
    group by t1.field1, t1.field2, t2.date1;
    
    select t1.field1, t1.field2, t2.date1, sum(t3.field2)
    from table1 t1 join
         (select t2.field1, max(date1) as date1
          from table2 t2
          group by t2.field1
         ) t2
         on t1.field1 = t2.field1 join
         table3 t3
         on t1.field1 = t3.field1
    group by t1.field1, t1.field2, t2.date1;