我有Users
的表格,其中包含培训预算
ID | UserID | FName | SName | Dept | Budget
1 | 1 | John | Smith | CS | 1000
2 | 2 | Ian | Caine | CS | 2500
3 | 3 | Jane | Kelly | ED | 1000
4 | 1 | John | Smith | EQ | 1000
5 | 2 | Ian | Caine | EQ | 2500
6 | 3 | Jane | Kelly | CS | 1000
然后我有另一张表Courses
来存储他们所采取的课程;
ID | UserID | Course | Date | Dept |Cost
1 | 1 | CS01 | 1/4/18 | CS | 100
2 | 2 | CS01 | 1/4/18 | CS | 100
3 | 1 | CS02 | 10/4/18 | CS | 75
4 | 2 | CS02 | 10/4/18 | CS | 75
5 | 1 | CS01 | 1/4/18 | EQ | 100
我想在顶部创建一个包含User
信息的表单,在底部创建一个Courses
的子表单,例如
UserID | FName | SName | Dept | Budget
1 | John | Smith | CS | 1000
subfrm
Course | Date | Cost | Balance Remaining
CS01 | 1/4/18 | 100 | 900
CS02 | 10/4/18 | 75 | 825
[更新]我坚持使用子窗体的基础查询,以下是我正在玩的SQL;
SELECT USerID, Amount,
(SELECT Sum(tbl_Courses.Cost) AS Total
FROM tbl_Courses
WHERE tbl_Courses.ID <= t1.ID) AS Total
FROM tbl_Courses AS T1
但是这给了我一个完整的运行总计而不是UserID和Dept的运行总计。
答案 0 :(得分:0)
只需将条件添加到子查询的WHERE
子句并加入用户表以检索预算值,即可将查询与所需的分组相关联。
SELECT u.UserID, c.Date, c.Cost,
u.Budget -
(SELECT Sum(sub.Cost)
FROM tbl_Courses sub
WHERE sub.ID <= c.ID
AND sub.UserID = c.UserID
AND sub.Dept = c.Dept) AS [Budget Remaining]
FROM tbl_Users u
INNER JOIN tbl_Courses AS c
ON u.UserID = c.UserID AND u.Dept = c.Dept
对于可更新的查询,请使用域聚合DSum
:
SELECT u.UserID, c.Date, c.Cost,
u.Budget -
DSum("sub.Cost", "tbl_Courses", "ID <= " & c.ID &
" AND UserID = " & c.UserID &
" AND Dept = '" & c.Dept & "'") AS [Budget Remaining]
FROM tbl_Users u
INNER JOIN tbl_Courses AS c
ON u.UserID = c.UserID AND u.Dept = c.Dept