SQL-汇总可能不会出现在WHERE子句中,除非它出现在HAVING子句或选择列表中包含的子查询中

时间:2019-08-20 06:58:31

标签: sql

我只想更新我的TicketStatus列(如果它在最新的DatePosted之前的7天到达),在我的Dateposted中添加MAX时会显示错误。

UPDATE  a
SET     a.TicketStatus = @Status
FROM    TicketTb a
        LEFT JOIN TicketConvo b
            ON b.TicketID= a.TicketNumber
            where  DATEDIFF(day,MAX(b.DatePosted),GetDate() ) >= 7

3 个答案:

答案 0 :(得分:2)

与分组依据一起使用

UPDATE  a
SET     a.TicketStatus = @Status
FROM    TicketTb a
        LEFT JOIN TicketConvo b
            ON b.TicketID= a.TicketNumber group by a.TicketNumber
            having  DATEDIFF(day,MAX(b.DatePosted),GetDate() ) >= 7

答案 1 :(得分:2)

尝试一下:

UPDATE  a
SET     a.TicketStatus = @Status
FROM    TicketTb a
        LEFT JOIN ( select TicketID,MAX(b.DatePosted) as DatePosted TicketConvo  group by TicketID )b
            ON b.TicketID= a.TicketNumber
            where  DATEDIFF(day,DatePosted ,GetDate() ) >= 7

答案 2 :(得分:0)

您可以尝试使用此dml脚本。

UPDATE  TicketTb
SET     TicketStatus = @Status
WHERE  TicketNumber in (Select a.TicketNumber FROM TicketTb a
                            LEFT JOIN TicketConvo b
                            ON b.TicketID= a.TicketNumber
                            GROUP BY a.TicketNumber
                            HAVING  DATEDIFF(day,MAX(b.DatePosted),GetDate() ) >= 7)