问题
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