sql - Grouping data with specified max data -
good day, i'm sorry title. ok, example have data
outletasal outlettujuan remark externaldocno itemcode qty k-aeon k-ar4 dus 20 closing wfs170402776 2 k-aeon k-ar4 dus 20 closing wfs170402758 1 k-aeon k-ar4 dus 20 closing wfs170402790 1 k-aeon k-ar4 dus 20 closing wfs170502796 2 k-aeon k-ar4 dus 20 closing whs170400011 1 k-aeon k-ar4 dus 20 closing whs170400015 1 k-aeon k-ar4 dus 21 closing whs170400015 1
so, want achieve (grouping outletasal,outlettujuan,remark,extrnaldocno maximum 5 records, if there 6 records make 2 headers)
#header outletasal outlettujuan remark externaldocno headerid k-aeon k-ar4 dus 20 closing 1 k-aeon k-ar4 dus 20 closing 2 k-aeon k-ar4 dus 21 closing 3 #detail itemcode qty headerid wfs170402776 2 1 wfs170402758 1 1 wfs170402790 1 1 wfs170502796 2 1 whs170400011 1 1 whs170400015 1 2 whs170400015 1 3
for have query header
part
select ltrim(rtrim(outletasal)) outletasal,ltrim(rtrim(outlettujuan)) outlettujuan,remark, row_number() over(order outletasal,outlettujuan,remark asc) urut #tempgroup importcsvdo group outletasal ,outlettujuan , remark ,externaldocno
with query above , not expected (please check above)
outletasal outlettujuan remark urut k-aeon k-ar4 dus 20 1 k-aeon k-ar4 dus 21 2
thanks in advance , sorry bad english.
you use modulo (%)
in sql this
;with temp ( select *, row_number() over(partition outletasal ,outlettujuan , remark ,externaldocno order ic.id) rn importcsvdo ic ) select outletasal, outlettujuan, remark, externaldocno, row_number() over(order outletasal,outlettujuan,remark asc) headerid, t.rn groupheaderid temp t t.rn % 5 = 1
and detail table (assuming have header table)
;with temp ( select *, row_number() over(partition outletasal ,outlettujuan , remark ,externaldocno order ic.id) rn @sampledata ic ) select t.itemcode, qty, ht.headerid headerid temp t inner join @headertable ht on t.outletasal = ht.outletasal , t.outlettujuan = ht.outlettujuan , t.remark = ht.remark , t.externaldocno = ht.externaldocno , (t.rn - 1) / 5 = (ht.groupheaderid - 1) / 5
see demo here
Comments
Post a Comment