简体   繁体   中英

SQL Update using subquery

I'm trying to update a table using a sub query but it's not recognising the table alias, when I try and run it a box pops up with 't1.rDate', my query is:

 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#;

Example:

   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

I think you want a correlated subquery:

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#;

Try this:

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

EDITED CODE :

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#;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM