MSACCESS/SQL查找表用于基于Current Table.field的总和



上周我一直在与许多尝试解决方案作战。我想根据桌子中的唯一名称,并根据这些总和将目前的舞蹈水平返回。最终,我想将返回的舞蹈水平与客户表中的舞蹈水平与客户进行比较,并仅显示两个舞蹈水平不同的记录(根据当前的积分总和,存储的舞蹈水平和计算出的舞蹈水平。

最终解决方案将是使用ADODB连接到MSACCESS DB(2013)的网页。但是对于初学者来说,只希望它在MSACCESS中工作。

我有一个带有以下表格的MSACCESS DB(2013)。

PointsAllocation
CustomerID  Points
100            2
101            1
102            1
100            1
101            4
DanceLevel
DLevel           Threshold
Beginner            2
Intermediate        4
Advanced            6
Customer
CID   Firstname Dancelevel1
100   Bob      Beginner
101   Mary     Beginner
102   Jacqui   Beginner

我想通过使用第一表中的积分总和为每个客户找到当前的dlevel。我第一个...

SELECT SUM(Points), CustomerID  FROM PointsAllocation GROUP BY CustomerID

效果很好,每个客户为我提供了总积分。然后,我可以将其连接到客户表以获取人员名称。完美。

现在,我想将DLEVEL从Dancelevel表中添加到结果中,其中总和用于查找阈值而不超过值,因此我得到以下内容:

(1)     (2)     (3)        (4)
Bob     3      Beginner   Intermediate
Mary    5      Beginner   Advanced
Where...
(1) Customer.Firstname
(2) SUM(PointsAllocation.Points)
(3) Customer.Dancelevel1
(4) Dancelevel.DLevel

jacqui没有显示出她的积分总和小于或等于2,从而给她一个舞蹈水平,这已经与客户桌上的dancelevel1匹配。

有人任何想法吗?

您可以从客户表开始,因为您想列出每个客户。然后,剩下的子查询可以计算舞蹈水平和点总数。最内向的子查询总计得分,然后加入有效的舞蹈水平,并从舞蹈水平中选择最大阈值。然后在阈值的阈值中再次加入Dancelevel表,以获取级别的描述。

Select Customer.Firstname,
  CustomerDanceLevels.Points,
  Customer.Dancelevel1,
  Dancelevel.DLevel
from Customer
left join
  (select CustomerID, Points, Min(Threshold) Threshold
  from
      (select CustomerID, sum(Points) Points
      from PointsAllocation
      group by CustomerID
      ) PointsTotal
    left join DanceLevel
    on PointsTotal.Points <= DanceLevel.Threshold
  group by CustomerID, Points
  ) CustomerDanceLevels
on Customer.CID = CustomerDanceLevels.CustomerID
left join DanceLevel
on CustomerDanceLevels.Threshold = DanceLevel.Threshold