帮助这个查询

时间:2010-10-28 11:06:16

标签: sql sql-server tsql

请你看看这个问题并指出我做错了什么:

update @output
set fromdate = o.fromdate,
    todate = o.todate
from
(
    select fromdate, max(todate)
    from @output as o
    left join status as es on
        o.number = es.empid and
        o.ccode = es.compcode and
        @status = es.status
)

我正在尝试使用包含max(todate)的记录来更新@output。我得到的错误是:

Msg 156,Level 15,State 1,Procedure CHP_OR_PENSIONEMPLOYEEENROLMENT_842,138行 关键字“select”附近的语法不正确。

3 个答案:

答案 0 :(得分:3)

以下脚本应执行更新。

UPDATE  @output
SET     fromdate = om.fromdate
        , todate = om.todate
FROM    @output o
        INNER JOIN (
          SELECT  o.number
                  , o.fromdate, 
                  , todate = MAX(todate)
          FROM    @output as o
                  LEFT OUTER JOIN status as es on
                      o.number = es.empid and
                      o.ccode = es.compcode and
                      @status = es.status
        ) om ON om.number = o.number

注意:我认为o.number是@output的主键

答案 1 :(得分:1)

UPDATE
  [output]
SET
  todate = MAX([es].todate)  /* I've assumed you want to gather this from [es] */
FROM
  @output as [output] 
LEFT JOIN
  status  as [es]
    on  [es].empid    = [output].number
    and [es].compcode = [output].ccode
    and [es].status   = @status
GROUP BY
  [output].<put your primary key field(s) here>

要么

UPDATE
  [output]
SET
  todate = (
             SELECT
               MAX(todate)
             FROM
               status
             WHERE
                   status.empid    = [output].number
               and status.compcode = [output].ccode
               and status.status   = @status
           )
FROM
  @output AS [output]

答案 2 :(得分:0)

DECLARE @output TABLE
        (
        number INT,
        fromdate DATETIME,
        todate DATETIME
        )
INSERT
INTO    @output
VALUES  (1, '2010-01-01', '2011-01-01')
INSERT
INTO    @output
VALUES  (1, '2010-02-01', '2010-11-01')
INSERT
INTO    @output
VALUES  (1, '2010-03-01', '2010-12-01')
INSERT
INTO    @output
VALUES  (2, '2010-01-01', '2011-01-01')
INSERT
INTO    @output
VALUES  (2, '2010-01-01', '2012-01-01')
;
WITH    q AS
        (
        SELECT  todate, MAX(todate) OVER (PARTITION BY number) AS maxtodate
        FROM    @output
        )
UPDATE  q
SET     todate = maxtodate

SELECT  *
FROM    @output