根据计数结果和条件更新访问SQL更新

时间:2012-08-14 20:33:04

标签: sql join conditional ms-access-2010

昨天我得到了关于这个SQL语句的帮助,并且它工作得非常好......现在我正在尝试使用此查询中的数据更新另一个表上的两列。

以下是我的查询:

SELECT x.TechID,
       Count(*) AS cnt,
       tblEmployeeData.LName,
       tblEmployeeData.Pernr,
       tblEmployeeData.Occurrences,
       tblEmployeeData.Standing
FROM   tblEmployeeData
       INNER JOIN tblOccurrence AS x
         ON tblEmployeeData.TechID = x.TechID
WHERE  ( ( ( x.OccurrenceDate ) BETWEEN Dateadd("m", -6, Date()) AND Date() )
         AND ( ( EXISTS (SELECT *
                         FROM   tblOccurrence AS y
                         WHERE  y.TechID = x.TechID
                                AND Dateadd ("d", -1, x.[OccurrenceDate]) = y.[OccurrenceDate]) ) = False ) )
GROUP  BY x.TechID,
          tblEmployeeData.LName,
          tblEmployeeData.Pernr;

我想要做的是获取结果并更新tblEmployeeData两列。一列(tblEmployeeData.Occorrences)将是'cnt'表示的值......然后是困难的部分......列tblEmployeeData.Standing将使用'cnt'中的值进行更新,如下所示:

0-3 = "Good"
4-5 = "Verbal Warning"
6-7 = "Written Warning"
8 = "Final Written Warning"
9+ = "Termination" 

这已经是一个很大的SQL语句了,这已经超出了我的想法!

1 个答案:

答案 0 :(得分:0)

您可以将查询包装在另一个查询中:

SELECT TechID, Rank FROM Rank,
(SELECT x.TechID, Count(*) AS cnt, tblEmployeeData.LName, 
    tblEmployeeData.Pernr, tblEmployeeData.Occurrences, tblEmployeeData.Standing
FROM tblEmployeeData
INNER JOIN tblOccurrence AS x ON tblEmployeeData.TechID = x.TechID
WHERE (((x.OccurrenceDate) Between DateAdd("m",-6,Date()) And Date())
  AND ((Exists     
    (SELECT * FROM tblOccurrence AS y  WHERE y.TechID = x.TechID AND DATEADD 
    ("d", -1, x.[OccurrenceDate]) = y.[OccurrenceDate]))=False))
GROUP BY x.TechID, tblEmployeeData.LName, tblEmployeeData.Pernr) a
WHERE a.Cnt BETWEEN Rank.Low And rank.High

我们的想法是将查询与Rank表一起使用,如下所示:

Low High    Rank
0   3       Good
4   5       Verbal Warning
6   7       Written Warning
8   8       Final Written Warning
9   99      Termination

编辑重新评论

这对我来说是一个粗略的模拟

SELECT a.TechID, tblRank.Rank FROM tblRank, (SELECT x.TechID, Count(*) AS cnt, tblEmployeeData.LName, 
    tblEmployeeData.Pernr, tblEmployeeData.Occurrences, tblEmployeeData.Standing
FROM tblEmployeeData
INNER JOIN tblOccurrence AS x ON tblEmployeeData.TechID = x.TechID
WHERE (((x.OccurrenceDate) Between DateAdd("m",-6,Date()) And Date()) AND ((Exists     
    (SELECT * FROM tblOccurrence AS y  WHERE y.TechID = x.TechID AND DATEADD 
    ("d", -1, x.[OccurrenceDate]) = y.[OccurrenceDate]))=False))
GROUP BY x.TechID, tblEmployeeData.LName, tblEmployeeData.Pernr, tblEmployeeData.Occurrences, tblEmployeeData.Standing) a
WHERE a.Cnt BETWEEN tblRank.Low And tblrank.High