添加SUM()表达式会导致我的Access查询停止工作

时间:2013-10-21 08:53:32

标签: c# winforms ms-access

在将SUM(b.[Amount_withDiscount])inner join on tables添加到之前正在运行的查询后,我收到了选择查询的错误消息。现在我希望查询也返回相关表中该列的总和。我哪里出错?

  

您尝试执行的查询不包含指定的表达式&#p; p。[PFirstName]& ' ' &安培; 。P [PLastName]'作为集合函数的一部分。

工作查询

string sql = "SELECT p.[PFirstName]&' '&p.[PLastName] as [Patient Name],p.[Age],p.[BirthDate],p.[MobileNo]&' / '&p.[LandlineNo] as [Contact Number] FROM Patient_Registration p WHERE datepart('m',p.[RegDate])=@month AND datepart('yyyy',p.[RegDate])=@year AND p.DoctorID=" + drId;   

添加sum和内部联接后的查询

string sql = "SELECT p.[PFirstName]&' '&p.[PLastName] as [Patient Name],p.[Age],p.[BirthDate],p.[MobileNo]&' / '&p.[LandlineNo] as [Contact Number], SUM(b.[Amount_withDiscount]) as [Payable Amount] FROM Patient_Registration p INNER JOIN Bill_Master b on p.[PatientID]=b.[Patient_ID] WHERE datepart('m',p.[RegDate])=@month AND datepart('yyyy',p.[RegDate])=@year AND p.DoctorID=" + drId;     

1 个答案:

答案 0 :(得分:1)

当您添加SUM()表达式时,您将查询从常规选择查询更改为聚合查询,该查询期望每个输出字段为

  • 聚合函数的一部分(SUM()MAX()等)或
  • 包含在GROUP BY子句中(查询中不存在)。

在这种情况下,对于一笔款项,您最好使用DSum()代替SUM(),例如

string sql = "SELECT p.[PFirstName]&' '&p.[PLastName] as [Patient Name],p.[Age],p.[BirthDate],p.[MobileNo]&' / '&p.[LandlineNo] as [Contact Number], DSum(\"Amount_withDiscount\",\"Bill_Master\",\"Patient_ID=\" & p.[PatientID]) as [Payable Amount] FROM Patient_Registration p WHERE datepart('m',p.[RegDate])=@month AND datepart('yyyy',p.[RegDate])=@year AND p.DoctorID=" + drId;