如何从之前选择的表的一部分中选择

时间:2019-04-08 08:42:00

标签: sql sql-server select

因为我要从链接的insql服务器收集数据,所以我应该选择表的一部分并对其进行处理。但是,当我想从子表中进行条件选择时,会收到“无效的对象名称错误”,这不应该是因为我将其设置为“ AS”

    SELECT * from (
    SELECT * FROM [Runtime].[dbo].[History]
    where TagName like '%L8.CipPhase%' and DateTime >= DATEADD(HOUR, -12, GETDATE())
    ) as t 
    WHERE t.[DateTime] >= 
    (SELECT MAX(t.[DateTime]) FROM t
    where TagName like '%L8.CipPhase%' and t.[DateTime] < 
    (SELECT MAX(t.[DateTime]) from t
    where TagName like '%L8.CipPhase%' and t.Value = 0))

3 个答案:

答案 0 :(得分:1)

您正在引用t-它是从子查询中创建的别名,在FROM子句中的另外两个子查询中作为表-是不允许的,它认为t存在真实的表名。要以这种方式使用它,您必须创建一个通用表表达式(CTE)。

例如

With t as (
    SELECT * FROM [Runtime].[dbo].[History]
    where TagName like '%L8.CipPhase%' and DateTime >= DATEADD(HOUR, -12, GETDATE())
)
    SELECT * from t
    WHERE t.[DateTime] >=  (
                            SELECT MAX(t.[DateTime]) 
                            FROM t
                            where TagName like '%L8.CipPhase%' 
                            and t.[DateTime] < (
                                 SELECT MAX(t.[DateTime]) 
                                 from t
                                 where TagName like '%L8.CipPhase%' 
                                 and t.Value = 0
                            )
    )

答案 1 :(得分:0)

T不是表,它是子查询的别名。因此,在where条件中,您需要在检索最大日期的地方包括表名。

   SELECT * from (
    SELECT * FROM [Runtime].[dbo].[History]
    where TagName like '%L8.CipPhase%' and DateTime >= DATEADD(HOUR, -12, GETDATE())
    ) as t 
    WHERE t.[DateTime] >= 
    (SELECT MAX(t.[DateTime]) FROM [Runtime].[dbo].[History] t
    where TagName like '%L8.CipPhase%' and DateTime >= DATEADD(HOUR, -12, GETDATE() and t.[DateTime] < 
    (SELECT MAX(t.[DateTime]) from [Runtime].[dbo].[History] t
    where TagName like '%L8.CipPhase%' and DateTime >= DATEADD(HOUR, -12, GETDATE() and t.Value = 0))

答案 2 :(得分:0)

使用临时表:

SELECT * into #Temp FROM [Runtime].[dbo].[History]
where TagName like '%L8.CipPhase%' and DateTime >= DATEADD(HOUR, -12, GETDATE())
declare @DateTime DateTime


SELECT @DateTime=MAX(t.[DateTime]) 
FROM #Temp
where TagName like '%L8.CipPhase%' and t.[DateTime] < 
(SELECT MAX(t.[DateTime]) from #Temp
where TagName like '%L8.CipPhase%' and t.Value = 0)    

select * from #Temp 
    WHERE t.[DateTime] >= @DateTime