使用来自另一个子查询中的子查询的列&在子查询中选择多个列

时间:2013-04-23 21:07:44

标签: sql sql-server

请查看下面的SQL查询:

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

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

另一个问题是如何在第一个子查询中选择多个列?或许喜欢 (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

1 个答案:

答案 0 :(得分: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;