以一对多关系连接两个 sql table,但想要第二个 table 的最大值

Joining two sql tables with a one to many relationship, but want the max of the second table

我正在尝试加入两个 tables,其中一个是独特的功能,秒是在与独特功能相关的几个日期进行的读数。我想要第一个 table 中的所有记录加上最近的阅读。在添加形状字段之前,我能够得到我正在寻找的结果。通过使用代码

SELECT
   Table1.Name, Table1.ID, Table1.Shape, 
   Max(Table2.DATE) as Date 
FROM         
   Table1 
LEFT OUTER JOIN
   Table2 ON Table1.ID = table2.ID
GROUP BY
   Table1.Name, Table1.ID, Table1.Shape

形状字段是几何类型,我收到错误

'The type "Geometry" is not comparable. It can not be use in the Group By Clause'

所以我需要换一种方式,但不确定如何。

下面是两个 table 的示例和所需的结果。

Table1
Name| ID |Shape
AA1 | 1  | X
BA2 | 2  | Y
CA1 | 3  | Z
CA2 | 4  | Q

Table2
ID | Date
1  | 5/27/2013
1  | 6/27/2014
2  | 5/27/2013
2  | 6/27/2014
3  | 5/27/2013
3  | 6/27/2014

我想要的结果是

Name| ID |Shape |Date
AA1 | 1  | X    | 6/27/2014
BA2 | 2  | Y    | 6/27/2014
CA1 | 3  | Z    | 6/27/2014
CA2 | 4  | Q    | Null

尝试将几何体转换为 varchar。

Select Table1.Name, Table1.ID, cast(Table1.Shape as varchar(1)) AS Shape, Max(Table2.DATE) as Date 

FROM         Table1 LEFT OUTER JOIN
                      Table2 ON Table1.ID = table2.ID

Group By Table1.Name, Table1.ID,  cast(Table1.Shape as varchar(1))

您可以在 CTE 中对 Table2 进行聚合,找到每个 ID 的 MAX(DATE),然后将该结果加入 Table1:

WITH AggregatedTable2(ID, MaxDate) AS
(
    SELECT 
        ID, MAX(DATE) 
    FROM 
        Table2 
    GROUP BY 
        ID
)
SELECT
    t1.ID, t1.Name, t1.Shape, t2.MaxDate
FROM
    Table1 t1
LEFT JOIN
    AggregatedTable2 t2 ON t1.ID = t2.ID

试试这个:

SELECT  t1.Name
        , t1.ID
        , t1.Shape
        , MAX(t2.Date) As Date
FROM    Table1 AS t1
LEFT JOIN Table2 AS t2
        ON  t2.ID = t1.ID
GROUP
    BY  t1.Name
        , t1.ID
        , t1.Shape