从两个表中选择一个XML

时间:2012-03-29 08:30:29

标签: sql xml sqlgeography

我正在尝试执行以下SQL:

SELECT * FROM Table2
INNER JOIN
    (SELECT * FROM Table1
    INNER JOIN
    (SELECT MAX(DateTime) AS LastMeasurement, MeasurementId as LastMeasurementId
    FROM Table1 GROUP BY MeasurementId) as lastMeasurement
    ON (Table1.MeasurementId = lastMeasurement.LastMeasurementId) 
    AND (Table1.DateTime = lastMeasurement.LastMeasurement)) as hLastMeasurement
ON Table2.Id = hLastMeasurement.Id
ORDER BY Table2.Id ASC

这很好用,但是因为我想以XML格式获得结果并且不得不投射地理列,所以我将第一行更改为:

SELECT Name, Description, CAST(Location as nvarchar(MAX)) FROM Table2

并将此行添加到最后:

FOR XML RAW ('Object'), ROOT ('Objects'), ELEMENTS

现在我正在获取XML,但仅使用表2中的数据 欢迎任何建议。

1 个答案:

答案 0 :(得分:0)

显然,如果要显示其他表中的数据,则必须以这种方式选择这些列。 IO通常使用MYSQL,因此这是我通常使用的方式。但是如果您使用的是oracle或其他数据库,那么您必须选择正确的别名来显示您希望的自定义​​列。请参阅使用sql server {{的连接的基本示例3}}

SELECT Table2.Name,Table2.Description,lastMeasurement.MeasurementId 

FROM Table2 t2
    INNER JOIN
        (SELECT * FROM Table1
        INNER JOIN
        (SELECT MAX(DateTime) AS LastMeasurement, MeasurementId as LastMeasurementId
        FROM Table1 GROUP BY MeasurementId) as lastMeasurement
        ON (Table1.MeasurementId = lastMeasurement.LastMeasurementId) 
        AND (Table1.DateTime = lastMeasurement.LastMeasurement)) as hLastMeasurement
    ON Table2.Id = hLastMeasurement.Id
    ORDER BY Table2.Id ASC