0

请看下面的 SQL 查询:

我想存储列值log_LogId(第 6 行),@startlog以便稍后在第 15 行中使用它。或者还有其他方法可以实现吗?

我不能写@log_LogId = log_LogId在第 6 行。它显示语法错误。

另一个问题是如何在第一个子查询中选择多个列?也许喜欢 (SELECT TOP 1 log_LogId, log_Cost .....

提前致谢。

DECLARE @startlog INT   
SELECT 
    log_VehicleId AS gpsId,
    log_LogId AS ignOnLogId,
    (SELECT TOP 1
        log_LogId ---Set this value to @startlog so that I can use this in "HERE"
            --- Also Select another column here
        FROM VehicleLog
        WHERE log_Eventid = 6012 AND log_LogId > v2.log_LogId 
        AND log_VehicleId = v2.log_VehicleId
    ) ignOffLogId,
    (SELECT SUM(CAST(log_COG AS FLOAT))
        FROM VehicleLog
        WHERE log_LogId >= v2.log_LogId
        AND log_LogId <= @startlog ---**HERE**
    )
from VehicleLog v2
WHERE log_Eventid = 6011 AND log_LogId < 300
4

1 回答 1

0

您可以按如下方式使用 CTE(公用表表达式):

;WITH CTE_V2 AS

(

    SELECT

        log_VehicleId 
        , log_LogId
    FROM
        VehicleLog

    WHERE 
        log_Eventid = 6011 AND log_LogId < 300

)

, CTE_IGN_OFF AS

(

    SELECT TOP 1

        log_LogId ---Set this value to @startlog so that I can use this in "HERE"

        ,log_OtherColumn    --- Also Select another column here

    FROM 
        VehicleLog

    WHERE 
        log_Eventid = 6012 
        AND log_LogId > (SELECT MAX(CTE_V2.log_LogId) 
                FROM CTE_V2 WHERE VehicleId = CTE_V2.log_VehicleId)
)
, CTE_COG AS
(
    SELECT 
        log_VehicleId AS gpsId
        , log_LogId AS ignOnLogId
        , SUM(CAST(log_COG AS FLOAT)) sum_COG
        FROM 
        VehicleLog
        WHERE 
        log_LogId >= (SELECT MAX(CTE_V2.log_LogId) 
                FROM CTE_V2 WHERE VehicleId = CTE_V2.log_VehicleId)
            AND log_LogId <= (SELECT TOP 1 log_OtherColumn FROM CTE_IGN_OFF)
    GROUP BY
        log_VehicleId
        , log_LogId
)
SELECT * FROM  CTE_COG;
于 2013-04-23T21:38:55.460 回答