Having trouble creating a view in Microsoft SQL Server Management Studio

半腔热情 提交于 2021-02-20 18:53:32

问题


I'm new to sql and am struggling to make a view. This works and pulls in the correct data I need as a table, but when I try it as a view I get the error:

SQL text cannot be represented in the grid pane and diagram pane.

SELECT [Data_Collector_ID],
       [Batch_Info_ID],
       [AssetTag],
       [DateTimeStamp],
       [Dust_Collector_DP]
FROM (
    SELECT [Data_Collector_ID],
           [Batch_Info_ID],
           [AssetTag],
           [DateTimeStamp],
           [Dust_Collector_DP],
           ROW_NUMBER() OVER (PARTITION BY [Batch_Info_ID] ORDER BY [DateTimeStamp] DESC) rn
    FROM [PLCLogging].[dbo].[Coater_Data_Collector]
) tmp
WHERE rn = 1 AND ([DateTimeStamp] > DATEADD(DAY, -7, GETDATE()))
    OR rn = 2 AND ([DateTimeStamp] > DATEADD(DAY, -7, GETDATE()))
ORDER BY DateTimeStamp DESC

Any idea how to get this to work as a view?

I'm trying to pull in the two most recent values for each Batch_Info_ID over the past week. If I need to provide more details please let me know.


回答1:


The following article talks about how complex queries cannot be interpreted by the view designer.

Open a new query window and copy and paste the following text and execute:

CREATE VIEW MyViewName
AS
    SELECT [Data_Collector_ID],
           [Batch_Info_ID],
           [AssetTag],
           [DateTimeStamp],
           [Dust_Collector_DP]
    FROM (
        SELECT [Data_Collector_ID],
               [Batch_Info_ID],
               [AssetTag],
               [DateTimeStamp],
               [Dust_Collector_DP],
               ROW_NUMBER() OVER (PARTITION BY [Batch_Info_ID] ORDER BY [DateTimeStamp] DESC) rn
        FROM [PLCLogging].[dbo].[Coater_Data_Collector]
    ) tmp
    WHERE rn = 1 AND ([DateTimeStamp] > DATEADD(DAY, -7, GETDATE()))
        OR rn = 2 AND ([DateTimeStamp] > DATEADD(DAY, -7, GETDATE()))
    ORDER BY DateTimeStamp DESC


来源:https://stackoverflow.com/questions/34636981/having-trouble-creating-a-view-in-microsoft-sql-server-management-studio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!