如果我运行此查询:
SELECT
[BBox]
,SUM(GrossPnL) AS 'Gross'
,SUM(SharesTraded) AS 'Shares'
,(SUM(GrossPnL)/SUM(SharesTraded)) AS 'CPS'
FROM [PrimusGroup].[dbo].[PrmsBlotter]
WHERE [RunType] = 'Backtesting'
GROUP BY [BBox]
对于有0股交易的情况,我得到0除错。
我试图解决这个问题:
SELECT
[BBox]
,SUM(GrossPnL) AS 'Gross'
,SUM(SharesTraded) AS 'Shares'
,(IF SUM(SharesTraded) > 0
(SUM(GrossPnL)/SUM(SharesTraded))
ELSE
SUM(GrossPnL)) AS 'CPS'
FROM [PrimusGroup].[dbo].[PrmsBlotter]
WHERE [RunType] = 'Backtesting'
GROUP BY [BBox]
但是我在sum附近得到了不正确的语法。难道我做错了什么?
答案 0 :(得分:4)
使用location.locationSchedule.scheduleType == 1
表达式。
case
答案 1 :(得分:1)
使用IIF:
SELECT
[BBox]
,SUM(GrossPnL) AS 'Gross'
,SUM(SharesTraded) AS 'Shares'
,(IIF SUM(SharesTraded) > 0,
(SUM(GrossPnL)/SUM(SharesTraded)),
SUM(GrossPnL)) AS 'CPS'
FROM [PrimusGroup].[dbo].[PrmsBlotter]
WHERE [RunType] = 'Backtesting'
GROUP BY [BBox]
答案 2 :(得分:0)
您可以使用IIF
SELECT [BBox]
,SUM(GrossPnL) AS 'Gross'
,SUM(SharesTraded) AS 'Shares'
,IIF(SUM(SharesTraded) > 0, SUM(GrossPnL)/SUM(SharesTraded), SUM(GrossPnL)) AS 'CPS'
FROM [PrimusGroup].[dbo].[PrmsBlotter]
WHERE [RunType] = 'Backtesting'
GROUP BY [BBox]
答案 3 :(得分:0)
如果'SharesTraded'= 0但是将0和1视为相同的值(你上面所做的)似乎是错误的,我看不出所需的输出是什么。
假设0是特殊情况,你的情况使用CASE WHEN情况并且只是使'ELSE'为NULL但我喜欢在可能的情况下使用'NULLIF'函数。
所以:
(SUM(GrossPnL)/SUM(SharesTraded)) AS 'CPS'
变为:
(SUM(GrossPnL)/NULLIF(SUM(SharesTraded),0)) AS 'CPS'
通过将SUM(SharesTraded)设置为0,当'SharesTraded'= 0时,这将导致'CPS'为NULL,从而解决错误。
不确定show-plan中的内容,但它有助于保持代码清晰简洁。