sql - 我想通过一个变量将两个查询合二为一
问题描述
我想通过一个变量将两个查询合二为一
ALTER PROCEDURE [dbo].[Balance]
@userId nvarchar(200)
AS
BEGIN
DECLARE @parchesQueryAdd decimal(18,2),@parchesQueryRemove decimal(18,2), @topupQuery decimal(18,2), @Balance decimal(18,2), @totalamount decimal(18,2)
/****** this two Querys starts ******/
SET @parchesQueryAdd = (SELECT SUM(Amount * CurrentBalanceCurrency) from UserBalance where BalanceForId = @userId and AmountType = 10)
SET @parchesQueryRemove = (SELECT SUM(Amount * CurrentBalanceCurrency) from UserBalance where BalanceForId = @userId and AmountType = 20)
/****** End ******/
SET @Balance = @parchesQueryAdd - @parchesQueryRemove
SET @topupQuery = (SELECT SUM(Amount * Quentity) from TopUpRecords where TopupById = @userId)
SET @totalamount= @Balance - @topupQuery
PRINT @totalamount
END
解决方案
您可以使用条件聚合函数来设置@Balance
而不是两个查询。
DECLARE
@parchesQueryAdd decimal(18,2),
@parchesQueryRemove decimal(18,2),
@topupQuery decimal(18,2),
@Balance decimal(18,2),
@totalamount decimal(18,2)
SELECT @Balance = SUM(CASE WHEN AmountType = 10 THEN Amount * CurrentBalanceCurrency ELSE 0 END)
- SUM(CASE WHEN AmountType = 20 THEN Amount * CurrentBalanceCurrency ELSE 0 END)
FROM UserBalance
WHERE BalanceForId = @userId
GROUP BY BalanceForId
SET @topupQuery = (SELECT SUM(Amount * Quentity) from TopUpRecords where TopupById = @userId)
SET @totalamount= @Balance - @topupQuery
PRINT @totalamount
推荐阅读
- swift - 我如何更好地定义一个区域来检测拖放节点?
- telegram - 使用 Telethon 从 event.message 对象获取发件人的用户名
- visual-studio - Visual Studio 一些颜色较深的代码
- python - 如何从一个热编码 csv 文件创建文件夹?
- sql - 通过 SQL Server 存储过程调度作业
- linux - MongoDB 不运行
- django - 使用加密和散列电子邮件作为用户名的 Django 用户模型
- python - 更改可变属性会更改类的每个实例中的该属性
- javascript - 如何在循环内声明类副本
- yaml - YAML - 获取有关新 yaml 属性的数据