在 SQL 服务器视图中插入重复行
Insert duplicate row in SQL Server view
我想知道是否可以在 SQL Server 2008 R2 中创建仅包含最后一列 (DateTime DESC) 的视图,但最后一行应该再次复制到视图中。
因此最终结果将是一个包含两行数据相同的视图。
select一行的查询很简单:
SELECT TOP 1 *
FROM Reporting
ORDER BY DateTime DESC
或
SELECT TOP 1 *
FROM Reporting
WHERE DateTime IN (SELECT MAX(DateTime)
FROM Reporting)
这returns只有一行,但我想在视图中再次复制这一行。
谢谢
尝试联合所有:
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC
UNION ALL
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC
上述答案中的语法无效。 UNION ALL
中的每个数据源中不允许有 ORDER BY
。你只能在最后陈述中有一个。所以,这是错误的:
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC
UNION ALL
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC
并且应该这样做:
SELECT * FROM (SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC)
UNION ALL
SELECT * FROM (SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC);
我会建议使用不同的方法。使用假数据源然后 cross apply
.
SELECT SI.*
FROM
(
SELECT 1
UNION ALL
SELECT 2
) DS ([col])
CROSS APPLY
(
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC
) SI;
您可以轻松地测试此语句的执行计划更好,只导致一次排序和索引扫描:
我想知道是否可以在 SQL Server 2008 R2 中创建仅包含最后一列 (DateTime DESC) 的视图,但最后一行应该再次复制到视图中。
因此最终结果将是一个包含两行数据相同的视图。
select一行的查询很简单:
SELECT TOP 1 *
FROM Reporting
ORDER BY DateTime DESC
或
SELECT TOP 1 *
FROM Reporting
WHERE DateTime IN (SELECT MAX(DateTime)
FROM Reporting)
这returns只有一行,但我想在视图中再次复制这一行。
谢谢
尝试联合所有:
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC
UNION ALL
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC
上述答案中的语法无效。 UNION ALL
中的每个数据源中不允许有 ORDER BY
。你只能在最后陈述中有一个。所以,这是错误的:
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC
UNION ALL
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC
并且应该这样做:
SELECT * FROM (SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC)
UNION ALL
SELECT * FROM (SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC);
我会建议使用不同的方法。使用假数据源然后 cross apply
.
SELECT SI.*
FROM
(
SELECT 1
UNION ALL
SELECT 2
) DS ([col])
CROSS APPLY
(
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC
) SI;
您可以轻松地测试此语句的执行计划更好,只导致一次排序和索引扫描: