使用子查询的SQL更新

时间:2019-05-30 14:46:05

标签: sql ms-access

我正在尝试使用子查询来更新表,但无法识别表别名,当我尝试运行它时,会弹出一个带有“ t1.rDate”的框,我的查询是:

 UPDATE Results SET odds4 = 
(SELECT SUM(IIF(odds >= 4, 1, 0)) FROM Results t1
GROUP BY t1.rDate, t1.rTime, t1.rTrack)
WHERE rDate = t1.rDate AND rTime = t1.rTime AND rTrack = t1.rTrack AND t1.rDate 
>= #2019/05/28#;

示例:

   rDate   | rTime | rTrack | horse   | odds | odds4
------------------------------------------------------
28/05/2019 | 13:00 | Ascot  | horse1  | 2.5  |  3
28/05/2019 | 13:00 | Ascot  | horse2  | 34   |  3
28/05/2019 | 13:00 | Ascot  | horse3  | 1.4  |  3
28/05/2019 | 13:00 | Ascot  | horse4  | 6    |  3
28/05/2019 | 13:00 | Ascot  | horse5  | 4    |  3
28/05/2019 | 14:30 | Epsom  | horse1  | 3    |  2
28/05/2019 | 14:30 | Epsom  | horse2  | 1.75 |  2
28/05/2019 | 14:30 | Epsom  | horse3  | 2    |  2
28/05/2019 | 14:30 | Epsom  | horse4  | 12   |  2
28/05/2019 | 14:30 | Epsom  | horse5  | 66   |  2

2 个答案:

答案 0 :(得分:1)

我认为您想要一个相关的子查询:

UPDATE Results
    SET odds4 = (SELECT SUM(IIF(t1.odds >= 4, 1, 0))
                 FROM Results t1
                 WHERE t1.rDate = Results.rDate AND
                       t1.rTime = Results.rTime AND
                       t1.rTrack = Results.rTrack
                )
WHERE Results.rDate >= #2019/05/28#;

答案 1 :(得分:0)

尝试一下:

UPDATE Results SET odds4 = 
                 CASE 
                    WHEN odds >= 4 THEN 1
                    ELSE 0
                 END 
WHERE rDate >= #2019/05/28#;

编辑代码:

UPDATE Results SET odds4 = (SELECT t1.odds4
 FROM
    (
     SELECT  rDate,
                     rTime,
                     rTrack,
                    SUM(IIF(odds >= 4, 1, 0)) AS odds4
      FROM Results
     GROUP BY rDate, rTime, rTrack
    ) AS t1

  WHERE Results.rDate = t1.rDate
    AND Results.rTime = t1.rTime
    AND Results.rTrack = t1.rTrack
)
    WHERE Results.rDate >= #2019/05/28#;