我是sql的新手并且正在努力寻找观点。这工作并提取我需要的正确数据作为表,但当我尝试作为一个视图我得到错误:
无法在网格窗格和图表窗格中表示SQL文本。
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
知道如何让它作为一种观点发挥作用吗?
我试图在过去一周内为每个Batch_Info_ID
提取两个最近的值。如果我需要提供更多详细信息,请告诉我。
答案 0 :(得分:4)
以下article讨论了视图设计器无法解释复杂查询的方式。
打开一个新的查询窗口并复制并粘贴以下文本并执行:
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