SQL设置子查询,其中来自主查询的值

时间:2014-02-26 10:39:37

标签: mysql sql sql-server datetime subquery

希望从主查询中获取子查询值中的where语句值。

这是我试图实现的减少版本,但它会给你一个想法。

SELECT  Date, Day, Year, 

(SELECT COUNT(*) AS [Moves]
FROM 
    (
    SELECT moves AS too
    FROM moveevent
    FULL OUTER JOIN job AS too ON moves = too.jobid
    WHERE  (moveevent.time >= [start] and moveevent.time <= [end])
UNION ALL
    SELECT moves AS frm
    FROM moveevent
    FULL OUTER JOIN job AS frm ON moves = frm.jobid
    WHERE  (moveevent.time >= [start] and moveevent.time <= [end])
    )   
    AS m
FULL OUTER JOIN job ON m.too = jobid
WHERE mainjobid = jobid
GROUP BY jobid) 
) 
      AS [Total Moves by Shift],


FROM    job
LEFT OUTER JOIN mainjob ON jobid = mainjobid

WHERE jobid = '12345' 
and [start] = '2013-05-25 12:45:00.000'
and [end] = '2013-05-25 17:45:00.000'

基本上我希望子查询中的起始值和结束值由主查询定义,但我不能让它们成为有效的列名。

名称“开始”和“结束”,这些不是任何表中的字段,只是组成,我希望能够在底部的主查询where子句中设置这些字段。

1 个答案:

答案 0 :(得分:2)

试试:

DECLARE @start DATETIME, @end DATETIME
SET @start = '2013-05-25 12:45:00.000'
SET @end = '2013-05-25 17:45:00.000'
       (SELECT COUNT(*) AS [Moves]
    FROM 
        (
        SELECT moves AS too
        FROM moveevent
        FULL OUTER JOIN job AS too ON moves = too.jobid
        WHERE  (moveevent.time >= @start and moveevent.time <= @end)
    UNION ALL
        SELECT moves AS frm
        FROM moveevent
        FULL OUTER JOIN job AS frm ON moves = frm.jobid
        WHERE  (moveevent.time >= @start and moveevent.time <= @end)
        )   
        AS m

我很快测试了它,但没有明确地测试过。请给我一个反馈。