我有一张包含多家公司版本信息的表格。
|Useful info | major | minor | week_id | company_id |
---------------------------------------|------------|
|************| 1 | 0 | 2015_01 | 1 |
|************| 1 | 1 | 2015_01 | 1 |
|************| 2 | 0 | 2015_01 | 1 |
|************| 1 | 0 | 2015_01 | 2 |
|************| 1 | 1 | 2015_01 | 2 |
因此,对于每周,我需要获取与上一版本相对应的信息(最大(主要,次要))
我试过了:
select * from my_table
where (major, minor) = max(major, minor)
group by compatny_id, week_id
它不起作用,因为max()
不应该采用多个参数。
所以我决定将(major, minor)
更改为100 * major + minor
。我试过了:
select * from my_table
where (company_id, week_id, 100 * major + minor) in
(
select sec_semaine_cinema_id, cpx_complexe_id, max(100 * dlo_version_major + dlo_version_minor)
from demande_log_dlo
group by sec_semaine_cinema_id, cpx_complexe_id
)
这个有效! 但:显然会强制进行全面扫描。
你有更好的解决方案吗?
(我正在使用Postgresql 9.3)
答案 0 :(得分:0)
您可以使用distinct on
select distinct on (company_id, week_id) t.*
from my_table t
order by company_id, week_id, major desc, minor desc;
如果您更喜欢使用更多标准SQL,请使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by company_id, week_id order by major desc, minor desc) as seqnum
from my_table t
) t
where seqnum = 1;