SQL UPDATE与CASE,GROUP BY和HAVING

时间:2012-08-14 23:35:58

标签: sql sql-server

下面的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和Having,但我已经看到了在Set和Join之前使用Select with Group By的示例。我无法让它发挥作用。

感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

UPDATE stu
SET tru = sub.letter
FROM
    stu JOIN (
    SELECT stu.sc, stu.sn,
        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
) sub ON stu.sc = sub.sc AND stu.sn = sub.sn

答案 1 :(得分:2)

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)