我的sql server数据库中的股票市场数据用于我的历史交易。这是表结构
表格列
我想知道的是连续N天我最终失败了。换句话说,就是我遇到的最大失败序列。我有4年的数据。 我有一个sql,它给我每日利润损失,但它太多的数据,以找到连续的连续几天输掉。分享下面的sql
select tradedate, sum(profitloss) as profitloss
from calls
where
group by TradeDate
order by ProfitLoss
--Create table
CREATE TABLE [dbo].[Calls](
[CallDate] [datetime] NOT NULL,
[StockName] [varchar](500) NOT NULL,
[Quantity] [int] NOT NULL,
[EntryPrice] [float] NOT NULL,
[ExitPrice] [float] NOT NULL,
[ProfitLoss] [float] NOT NULL
) ON [PRIMARY]
--Sample Data for a day
TradeDate StockName Profitloss
2012-10-05 09:19:00.000 HINDALCO -999.6
2012-10-05 09:19:00.000 CIPLA -999.6
2012-10-05 09:19:00.000 BPCL -999
2012-10-05 09:19:00.000 BANKBARODA 3256.25
2012-10-05 09:19:00.000 TATASTEEL 3493.5
2012-10-05 09:19:00.000 AMBUJACEM 6230.36
2012-10-05 09:19:00.000 JINDALSTEL 7953.01
答案 0 :(得分:0)
请试试这个
select tradedate, sum(profitloss) as profitloss
from calls
where
group by TradeDate
having sum(profitloss) < 0
order by tradedate desc
答案 1 :(得分:0)
我无法访问测试数据或SQL的风格,但这个粗略的想法应该适合您。适合您的数据和SQL方言。
使用
case when ( sum(profitloss) over ( rows between 1 preceding and 1 preceding) * sum(profitloss) over ( rows between current_row and current_row) ) > 0 then 0 else 1 end as sign_change_marker
然后count(*) over ( rows from current row to following unbound reset when sign_change_marker = 1)
计算从每个日期开始的赢或输的连胜长度