我需要以两种不同的货币(美元和玻利维亚诺)获得公司的业务量。我在存储过程中进行了两次查询,但它确实有效。我的问题是我不知道如何在一个独特的查询中合并它们,因为它们几乎是一样的。
SELECT @amount_dollars = ISNULL(SUM(Amount), 0.00)
FROM ProcessBatches
WHERE
CompanyId = @company_id
AND CONVERT(CHAR(8), DateProcess, 112) = @current_date
AND Currency = 'USD'
AND OperationTypeId NOT IN (17,18)
AND State IN ('P','W','N','A')
SELECT @amount_bols = ISNULL(SUM(Amount), 0.00)
FROM ProcessBatches
WHERE
CompanyId = @company_id
AND CONVERT(CHAR(8), DateProcess, 112) = @current_date
AND Currency = 'BOL'
AND OperationTypeId NOT IN (17,18)
AND State IN ('P','W','N','A')
我不是SQL的专家。提前致谢并抱歉我的英语(我正在学习)
答案 0 :(得分:6)
只需使用条件聚合:
SELECT @amount_dollars = COALESCE(SUM(CASE WHEN Currency = 'USD' THEN Amount END), 0.00) ,
@amount_bols = COALESCE(SUM(CASE WHEN Currency = 'BOL' THEN Amount END), 0.00)
FROM ProcessBatches
WHERE CompanyId = @company_id AND
CAST(DateProcess as date) = @current_date AND
Currency IN ('BOL', 'USD') AND
OperationTypeId NOT IN (17, 18) AND
State IN ('P', 'W', 'N', 'A');
注意:我更改了date
比较以使用date
数据类型。这比使用字符串比较要好得多。此外,转换为日期仍然允许使用索引(在SQL Server中)。