Firebird Query- Return first row each group

旧巷老猫 提交于 2019-12-01 23:13:19
Mark Rotteveel

In Firebird 2.5 you can do this with the following query; this is a minor modification of the second part of the accepted answer of the question you linked to tailored to your schema and requirements:

select   x.id,
         x.customerid, 
         x.dthrsale
    from sales x
    join (select customerid,
                 min(dthrsale) as first_sale
            from sales 
        group by customerid) p on p.customerid = x.customerid
                              and p.first_sale = x.dthrsale
order by x.id

The order by is not necessary, I just added it to make it give the order as shown in your question.

With Firebird 3 you can use the window function ROW_NUMBER which is also described in the linked answer. The linked answer incorrectly said the first solution would work on Firebird 2.1 and higher. I have now edited it.

Search for the sales with no earlier sales:

SELECT S1.*
FROM SALES S1
LEFT JOIN SALES S2 ON S2.CUSTOMERID = S1.CUSTOMERID AND S2.DTHRSALE < S1.DTHRSALE
WHERE S2.ID IS NULL

Define an index over (customerid, dthrsale) to make it fast.

So simple as:

select CUSTOMERID min(DTHRSALE) from SALES group by CUSTOMERID

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!