我有两张桌子:
Employee:
ID
SalaryPerDay
overTimeHoursPrice
.....
.....
Schedule:
ID
EmployeeID
Date
Attending (boolean)
loan
discount
overTimeHours
有多对一的关系
我想要一个返回的查询
[员工姓名]和
[sum(loan)]和
[sum(discount)]和
[sum(overTimeHours)]和
[count(参加)]参加= true和
[count(参加)* SalaryPerDay]和
[sum(overTimeHours)* overTimeHoursPrice]和
[(计数(参加)* SalaryPerDay)+(sum(overTimeHours)* overTimeHoursPrice) - (总和(折扣)) - (总和(贷款))]
1-其中Date> = [date1]和Date< = [date2]
2-其中Date> = [date1]和Date< = [date2]和EmployeeName = [name]
(date1和date2以及名称是参数)
答案 0 :(得分:0)
这样的事情可以解决这个问题......
SELECT
emp.EmployeeName, sum_loan, sum_discount, sum_overTimeHours, count_attending,
(count_attending*SalaryPerDay) as totalDayPay,
(sum_overTimeHours*overTimeHoursPrice) as totalOverTimePay,
((count_attending*SalaryPerDay) + (sum_overTimeHours*overTimeHoursPrice) -
sum_discount - sum_loan) as grandTotal
FROM Employee emp
INNER JOIN (SELECT
EmployeeID,
sum(loan) as sum_loan,
sum(discount) as sum_discount,
sum(overTimeHours) as sum_overTimeHours,
sum(iif(Attending,1,0)) as count_attending
FROM Schedule
WHERE Date >= {date1} and Date <= {date2}
GROUP BY EmployeeID
) sch
ON emp.ID = sch.EmployeeID
WHERE emp.EmployeeName = {name}
请注意两个WHERE
子句。您可以根据需要调整这些以实现两个不同的参数化限制。
编辑#1:
由于存储在Schedule.Attending
字段中的“布尔”的实际数值存在一些不确定性,我调整了上面的查询以明确地考虑布尔值。为此,我使用了特定于MSAccess的表达式函数IIF()
。这是一个更强大的解决方案,而不仅仅是假设该字段包含1
或0
。
编辑#2:
我还应该注意,语法会略有不同,具体取决于您使用它的位置。以上是派生表的“标准sql”语法(即INNER JOIN
个关键字后括号内的子查询)。如果您通过ODBC连接运行此查询,则上述语法有效。
但是,如果您尝试在Access中创建查询,则需要在子查询周围使用带有尾随句点[ ].
而不是括号( )
的方括号。所以而不是:
SELECT ... FROM Employee emp INNER JOIN (SELECT ... ) sch ON ...
使用它:
SELECT ... FROM Employee emp INNER JOIN [SELECT ... ]. sch ON ...
答案 1 :(得分:0)
我想你想要:
SELECT e.EmployeeName,
Sum(s.loan) AS SumOfloan,
Sum(s.discount) AS SumOfdiscount,
Sum(s.overTimeHours) AS SumOfoverTimeHours,
Sum(Abs([Attending])) AS Attnd,
Sum([SalaryPerDay]*Abs([Attending])) AS SalyAttnd,
Sum([overTimeHoursPrice]*[overtimehours]) AS OTCost,
Sum(([SalaryPerDay]*Abs([Attending])+[overTimeHoursPrice]*[overtimehours])-([loan]-[discount])) AS Due
FROM Employee e
INNER JOIN Schedule s ON e.ID = s.EmployeeID
WHERE s.Date Between [date1] And [Date2]
AND EmployeeName = [Name]
GROUP BY e.ID, e.EmployeeName
请注意,布尔值为0或-1,因此[SalaryPerDay] * Abs([Attending] = Salary * 1,如果参加或0,如果不参加。