如何按组限制SQL查询的结果

时间:2016-03-08 13:44:13

标签: python sql sqlite

我有这个问题:

select article_number, date, company, size, price 
from price 
order by article_number, company, date

产生这些结果:

('50240-20', '2016-03-08 13:06:12.872955', '2B', '20', '645,75')
('50240-20', '2016-03-08 13:13:55.311955', '2B', '20', '645,75')
('50240-20', '2016-03-08 13:47:13.737155', '2B', '20', '645,75')
('50240-20', '2016-03-08 13:51:32.677155', '2B', '20', '645,75')
('50240-20', '2016-03-08 13:06:12.872955', 'Bio', '20', '423,20')
('50240-20', '2016-03-08 13:13:55.311955', 'Bio', '20', '423,20')
('50240-20', '2016-03-08 13:47:13.737155', 'Bio', '20', '423,20')
('50240-20', '2016-03-08 13:51:32.677155', 'Bio', '20', '423,20') ...

我想限制每个article_numbercompany选项的结果,以便它只显示2个结果,其中有2个最后不同的日期。所以结果应该是这样的:

('50240-20', '2016-03-08 13:47:13.737155', '2B', '20', '645,75')
('50240-20', '2016-03-08 13:51:32.677155', '2B', '20', '645,75')

('50240-20', '2016-03-08 13:47:13.737155', 'Bio', '20', '423,20')
('50240-20', '2016-03-08 13:51:32.677155', 'Bio', '20', '423,20') ...

任何人都可以帮我怎么做?最后一个简单的限制2只会给出2个结果而不是每个"组"

THX!

3 个答案:

答案 0 :(得分:1)

你没有指定你的DBMS,所以对于ORACLE,POSTGRESQL,SQL-SERVER可以像这样使用ROW_NUMBER():

SELECT * FROM (
    select article_number, date, company, size, price ,
       ROW_NUMBER() OVER(PARTITION BY article_number,company ORDER BY date DESC) as rnk
    from price )
WHERE rnk <= 2
order by article_number, company, date

MYSQL的解决方案:

SELECT * FROM (
    select t.article_number, t.date, t.company, t.size, t.price , count(*) as rnk
    from price t
    INNER JOIN price s
    ON(t.article_number = s.article_number and t.company = s.company and t.date <= s.date)
    GROUP BY t.article_number,t.company,t.date,t.size,t.price
)
WHERE rnk <= 2
order by article_number, company, date

编辑:我看到它的sqlite,尝试MYSQL的第二个解决方案,它也适用于sqlite ..

答案 1 :(得分:0)

如果是甲骨文:

添加      ROW_NUMBER()OVER(由COLNAME按COLNAME排序)RN

作为列并将您的查询包装在SELECT查询中。在父查询中,然后使用RN列限制每组的结果。

答案 2 :(得分:0)

这是一个通用的解决方案,您可以在几乎所有不支持的RDMBS中使用LogEntries.Filter = null

partition by