Friday, July 13, 2012

Crystal Reports,how to use SQL to find first or nth row of every group

If you want to find the first row of every group in Crystal Reports you've got different options. 1 option is using

 If Previous ({table.GroupingField}) = ({table.GroupingField}) Then   
   False  
 Else  
   True  

But another option I like, is using the row_number function of Sql Server. With this function you can number your rows and have the row number reset depending on for example your group condition. Below is an example where I want the row number to reset if the column "SERNR" changes. I've also included the sql results so you can see the row number resetting if the "SERNR" changes. In Crystal Reports you simply check if row_number = 1 or 2 or 3 or which row you want to do something for.

 select row_number() over (Partition by em037.sernr order by em037.datum asc),  
 em037.*, em035.merk, em035.mtype, em035.numpl, em035.numpv, em035.machn, em035.chafn  
 from em037  
 inner join em035 on em035.sernr = em037.sernr  
 where em037.datum between '03/01/2012' and '06/30/2012' and  
 em037.sernr in ('W0L0AHM757G138179', 'WOLGT8EK8A1010638','WVGZZZ1TZ9W085082')  
 and em035.rtype = '002'