小编典典

具有CASE,GROUP BY和HAVING的SQL UPDATE

sql

下面的SELECT语句返回正确的数据。

SELECT stu.sc, stu.sn, COUNT(*) AS Total,
    CASE
      WHEN COUNT(*) = 3 Then 'Letter 1'
      WHEN COUNT(*) = 4 Then 'Letter 2'
      WHEN COUNT(*) = 5 Then 'Letter 3'
      ELSE 'SARB'
    END AS Letter  
FROM STU  join att ON (stu.SC = att.SC and stu.SN = att.SN)
WHERE att.al in ('c','t','u')
GROUP by stu.sc, stu.sn
HAVING COUNT(*) >= 3

我需要基于该查询执行UPDATE,但似乎无法弄清楚。我已经看了多个在线示例,这些示例与我所需要的相似,但是我无法使它正常工作。我需要能够做这样的事情…

UPDATE stu
SET stu.tru = 
   CASE
     When COUNT(*) = 3 Then 'Letter 1'
     When COUNT(*) = 4 Then 'Letter 2'
     When COUNT(*) = 5 Then 'Letter 3'
     ELSE 'SARB'
   END  
FROM stu  JOIN att
   on (stu.sc = att.sc and stu.sn = att.sn)
WHERE ATT.AL in ('c','t','u')
GROUP BY stu.sc, stu.sn
HAVING COUNT(*) >= 3

我知道我不能在Update语句中直接使用Group By and Haveing,但是我看到了一些示例,在这些示例中,他们在Set and
Join之前使用Select with Group By。我就是无法正常工作。

谢谢你的帮助。


阅读 170

收藏
2021-04-28

共1个答案

小编典典

WITH CTE AS (
  SELECT stu.sc, stu.sn, COUNT(*) AS Total,
      CASE
        WHEN COUNT(*) = 3 Then 'Letter 1'
        WHEN COUNT(*) = 4 Then 'Letter 2'
        WHEN COUNT(*) = 5 Then 'Letter 3'
        ELSE 'SARB'
      END AS Letter  
  FROM STU  join att ON (stu.SC = att.SC and stu.SN = att.SN)
  WHERE att.al in ('c','t','u')
  GROUP by stu.sc, stu.sn
  HAVING COUNT(*) >= 3
)
UPDATE stu
SET stu.tru = cte.Letter
FROM stu  JOIN cte
   on (stu.sc = cte.sc and stu.sn = cte.sn)
2021-04-28