在SQL Server视图中插入重复的行

时间:2018-07-10 06:29:12

标签: sql sql-server tsql views

我想知道是否可以在SQL Server 2008 R2中创建仅具有最后一列(DateTime DESC)的视图,但是该最后一行应再次在视图中复制。

所以最终结果将是一个具有两行具有相同数据的视图。

选择一行的查询很简单:

SELECT TOP 1 * 
FROM Reporting
ORDER BY DateTime DESC 

SELECT TOP 1 *
FROM Reporting
WHERE DateTime IN (SELECT MAX(DateTime) 
                   FROM Reporting)

这仅返回一行,但是我想再次在视图中重复此行。

谢谢

2 个答案:

答案 0 :(得分:6)

以上答案中的语法无效。 ORDER BY中的每个数据源都不允许有UNION ALL。在最后的声明中,您只能有一个。因此,这是错误的:

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;

您可以轻松地测试该语句的执行计划是否更好,因为它仅导致一次排序和索引扫描:

enter image description here

答案 1 :(得分:3)

尝试全部合并:

SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC 
UNION ALL
SELECT TOP 1 * FROM Reporting ORDER BY DateTime DESC