我尝试使用SQL进行计算。
我的数据库下面有前三列,我需要计算第四列:
Month |Name |Monthly Premium Paid |Number of consecutive months paid
Jan 2010 | Bob | Y | 1
Feb 2010 | Bob | Y | 2
Mar 2010 | Bob | N | 0
Apr 2010 | Bob | Y | 1
May 2010 | Bob | Y | 2
Jul 2010 | Bob | N | 0
答案 0 :(得分:1)
您可以尝试
select month, name, premiun_paid,
@row_number:=CASE
WHEN premiun_paid = 'Y' THEN @row_number + 1
ELSE 0
END consecutive_month
from table,(select @row_number:=0)r
参考:http://www.mysqltutorial.org/mysql-row_number/
模式(MySQL v5.7)
create table fiddle(month text,name text,
premium text,number int);
insert into fiddle values('Jan','Bob','Y',0),
('Feb','Bob','Y',0),
('Mar','Bob','N',0),
('Apr','Bob','Y',0),
('May','Bob','Y',0),
('June','Bob','N',0),
('Jul','Bob','Y',0),
('Aug','Bob','Y',0),
('Sep','Bob','Y',0);
查询#1
select month, name, premium,
@row_number:=CASE
WHEN premium='Y' THEN @row_number + 1
ELSE 0
END as consecutive_months
from fiddle,(select @row_number:=0)r;
| month | name | premium | consecutive_months |
| ----- | ---- | ------- | ------------------ |
| Jan | Bob | Y | 1 |
| Feb | Bob | Y | 2 |
| Mar | Bob | N | 0 |
| Apr | Bob | Y | 1 |
| May | Bob | Y | 2 |
| June | Bob | N | 0 |
| Jul | Bob | Y | 1 |
| Aug | Bob | Y | 2 |
| Sep | Bob | Y | 3 |