3

下面的 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 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 和 Have,但是我已经看到了他们在 Set 和 Join 之前使用 Select with Group By 的示例。我就是不能让它工作。

谢谢你的帮助。

4

2 回答 2

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
于 2012-08-14T23:39:33.917 回答
3
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)
于 2012-08-14T23:40:54.117 回答