我有一张这样的表:
RunId------CompanyId------NumberOfEmployees
1-------------------1-------------------10
2-------------------1-------------------10
3-------------------1-------------------8
4-------------------1-------------------9
5-------------------1-------------------11* (The first time company 1 expands to a size bigger than it's original size of 10)
6-------------------1-------------------12
3-------------------2-------------------50
4-------------------2-------------------55* (The first time company 2 expands to a size bigger than it's original size of 55)
5-------------------2-------------------54
1-------------------3-------------------100
2-------------------3-------------------100
3-------------------3-------------------100
我想找到每个CompanyID,该公司开始扩展到一个比原始起始尺寸更大的尺寸。
所以我想要这样的结果集:
CompanyId------StartRun------ExpansionRun-------StartingSize
1-------------------1-------------------5-------------------10
2-------------------3-------------------4-------------------50
非常感谢您提前的时间!
我也完成了我的研究并找到了这个答案Select rows where column value has changed,但这只是比较连续运行,而不是与公司开始的第一次运行进行比较。
答案 0 :(得分:1)
首先,您需要找到原始的起始大小。您可以从最小运行ID获得(大概)。然后另一个联接可以获得您正在寻找的信息:
select c.CompanyId, min(tt.runid) as FirstBigger_runid
from (select t.CompanyId, min(runid) as minrunid
from t
group by t.CompanyId
) c join
t t
on t.CompanyId = c.CompanyId and t.runid = c.minrunid left join
t tt
on tt.CompanyId = c.CompanyId and
tt.runid > c.minrunid and
tt.NumberOfEmployees > t.NumberOfEmployees
group by c.RunId;
这是公司第一次超过原始员工人数的情况。另一个连接将从该行获取所有其他信息。
以下是获取符合条件的运行ID的另一种方法:
select t.CompanyId, min(RunId) as theRunId
from (select t.*,
(select t2.NumberOfEmployees
from t t2
where t2.CompanyId = t.CompanyId
order by t2.RunId
limit 1
) as first_NumberOfEmployees
from t
having NumberOfEmployees > first_NumberOfEmployees
) t
group by t.CompanyId;