在一个字段上使用SQL SUM()在其他条件下使用其他字段(最有效的方式)

时间:2018-09-06 08:38:31

标签: sql-server tsql stored-procedures

我有一个存储过程来检索特定日期的总订单($$$),同时需要找出现金交易量与信用卡交易量的差额。 还有其他交易类型(例如,贝宝),但不需要返回(不要问我为什么)。

我有两种选择,全部写在1个查询中或通过游标。这是我的1条查询

SELECT @TotalOrder = SUM([TotalValue]),
       @TotalCash = (SELECT SUM([TotalValue]) FROM [dbo].[tblOrder] dbChild WHERE (dbChild.[OrderId] = dbMain.[OrderId]) AND (dbChild.[PaymentType] = 0)),
       @TotalCard = (SELECT SUM([TotalValue]) FROM [dbo].[tblOrder] dbChild WHERE (dbChild.[OrderId] = dbMain.[OrderId]) AND (dbChild.[PaymentType] = 1))
FROM [dbo].[tblOrder] dbMain
WHERE [PaymentDate] BETWEEN @StartDate AND @EndDate;

上面的查询可以吗?另外,我可以使用游标遍历每条记录并累积@ TotalOrder,@ TotalCash和@TotalCard。

SELECT [TotalValue], [PaymentType]
FROM [dbo].[tblOrder] dbMain
WHERE [PaymentDate] BETWEEN @StartDate AND @EndDate;

--then use cursor to loop through each of the record.

您怎么看?哪一种是最有效的方法?如果两者都不有效,您还有其他建议吗?

1 个答案:

答案 0 :(得分:4)

第一种方法很可能是最快的,但是您可以重构为使用单个查询:

SELECT @TotalOrder = SUM([TotalValue]),
       @TotalCash = SUM(CASE WHEN [PaymentType] = 0 THEN [TotalValue] ELSE 0 END)
       @TotalCard = SUM(CASE WHEN [PaymentType] = 1 THEN [TotalValue] ELSE 0 END)
FROM [dbo].[tblOrder] dbMain 
WHERE [PaymentDate] BETWEEN @StartDate AND @EndDate;