Sql server 如何在存储过程中使用多个select sum()查询
我有一个存储过程Sql server 如何在存储过程中使用多个select sum()查询,sql-server,stored-procedures,Sql Server,Stored Procedures,我有一个存储过程challan,它正在为fee challan工作 但是现在我想展示通过四个查询的帮助而收到的会费 我想在我的challan存储过程中添加这两个: create proc [dbo].[challan] @sessionid int, @month nvarchar(20) as select distinct student.Student_id as [A/c #], student.Student_Name, pa
challan
,它正在为fee challan工作
但是现在我想展示通过四个查询的帮助而收到的会费
我想在我的challan
存储过程中添加这两个:
create proc [dbo].[challan]
@sessionid int,
@month nvarchar(20)
as
select distinct
student.Student_id as [A/c #], student.Student_Name,
parent.father_name, class.class_numeric, invoice.Fee_description,
invoice.Amount, invoice.issue_date, invoice.month
from
student
join
parent on student.father_nic = parent.father_nic
join
allocate_class on student.Student_id = allocate_class.Student_id
join
class on class.class_id = allocate_class.class_id
join
session on allocate_class.session_id = session.session_id
join
invoice on student.Student_id = invoice.Student_id
where
session.session_id = @sessionid
and student.status = 'active'
and invoice.month = @month
order by
class.class_numeric asc
此查询用于收集当月费用,该费用将从应付款中减去,因为它已显示在challan
中:
SELECT
SUM(invoice.Amount)
FROM
invoice
WHERE
invoice.month = 'November-2019'
AND invoice.Student_id = '115'
现在我运行另外两个,它是发票表中所有challan
学生的总和,我必须从中减去当月费用
SELECT SUM(invoice.Amount)
FROM invoice
WHERE invoice.Student_id = '115
这用于汇总接收表中学生的所有已收费用:
SELECT SUM(Recipt.Paid_amount)
FROM Recipt
WHERE Recipt.Student_id = '115'
现在的问题是从上面的1)和2)个查询中减去3)个查询,然后放入
challan
存储过程的最后一个。您可以使用CASE条件来实现相同的结果
select
student.Student_id as [A/c #], student.Student_Name, parent.father_name,class.class_numeric, invoice.Fee_description, invoice.Amount, invoice. issue_date, invoice.month ,
SUM(CASE WHEN invoice.month = 'November-2019' AND invoice.Student_id = '115' THEN invoice.Amount ELSE 0 END)
from student
join parent on student.father_nic = parent.father_nic
join allocate_class on student.Student_id = allocate_class.Student_id
join class on class.class_id = allocate_class.class_id
join session on allocate_class.session_id = session.session_id
join invoice on student.Student_id = invoice.Student_id
where session.session_id= @sessionid AND student.status = 'active' AND invoice.month = @month
order by class.class_numeric asc
Msg 8120,第16级,状态1,第2行列“student.student_id”在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。选择SUM(当invoice.MOUNT='2019年11月'和invoice.student_id='115'然后是invoice.Amount ELSE 0 END时)从student.father\u nic=parent.father\u nic在student.student\u id=allocate\u class.student\u id在class.class\u id=allocate\u class.class\u id在allocate\u class.session\u id=session.session\u id在student.student\u id=invoice.student\u id在session.session\u id中加入会话student.status='active'和invoice.month=@monthbro它与我已经提到的查询号具有相同的工作方式..我的任务是从上述三个查询中进行一个查询,或者使用多个查询的存储过程