SQL 服务器 CE:如何将两个查询的结果合并到一行中?

SQL Server CE : how can I combine results of two queries into one row?

我有两个查询 return 来自不同表的单个值(并且没有以任何方式通过关系连接),我试图将两个查询的输出合并到一行中,但是我遇到了语法错误。这就是我正在尝试的:

SELECT
    (SELECT Timestamp As StartDate 
     FROM Events 
     WHERE Description = 'Inserted') AS StartDate,
    (SELECT TOP (1) Timestamp As EndDate 
     FROM DataStore 
     ORDER BY Timestamp DESC) AS EndDate

这就是我要返回的内容:

There was an error parsing the query. [ Token line number = 2,Token line offset = 2,Token in error = SELECT ]

查询 1 本身 returns:“2015-06-10 11:43:34.000”和查询 2 returns:“2015-06-11 13:59:47.000"

我想 return 单行两列,查询 1 的输出作为 "StartDate" 列,查询 2 的输出作为 "EndDate" 列。

declare @q1 as varchar(max)
declare @q2 as varchar(max)
SELECT @q1= Timestamp FROM Events WHERE Description = 'Inserted' 
SELECT TOP (1) @q2= Timestamp FROM DataStore Order by Timestamp DESC
select @q1 as StartDate, @q2 as EndDate

试试这个:

SELECT StartDate.StartDate, EndDate.EndDate
FROM
(SELECT Timestamp As StartDate FROM Events WHERE Description = 'Inserted') AS StartDate
CROSS JOIN
(SELECT TOP (1) Timestamp As EndDate FROM DataStore Order by Timestamp DESC) AS EndDate

与第二个查询不同,第一个查询可能 return 2 个或更多值。 尝试将 TOP (1) 也放在第一个查询中,因为我认为您只是在争取最佳结果。

SELECT
(SELECT TOP (1) Timestamp As StartDate FROM Events WHERE Description = 'Inserted') AS StartDate,
(SELECT TOP (1) Timestamp As EndDate FROM DataStore Order by Timestamp DESC) AS EndDate

看到这个 SQL Fiddle link 我做的测试。

SQL CE 不支持这样的嵌套 SELECT 语句,因此您必须使用两个 SELECT 语句并使用 UNION 或调用 ExecuteNonQuery 两次。