美好的一天,我很抱歉我的头衔。好的,举个例子我有这个数据
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
所以,我想实现这个目标(Grouping OutletAsal,OutletTujuan,Remark,ExtrnalDocNo最多5条记录,如果有6条记录则会产生2条标题)
#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
现在我有header
部分
SELECT LTRIM(RTRIM(OutletAsal)) OutletAsal,LTRIM(RTRIM(OutletTujuan)) OutletTujuan,Remark,
ROW_NUMBER() OVER(ORDER BY OutletAsal,OutletTujuan,Remark ASC) AS Urut
into #tempgroup
FROM ImportCsvDO
GROUP BY OutletAsal ,OutletTujuan , Remark ,ExternalDocNo
根据我上面的查询我得到了这个并不像我预期的那样(请在上面查看)
OutletAsal OutletTujuan Remark Urut
K-AEON K-AR4 DUS 20 1
K-AEON K-AR4 DUS 21 2
提前致谢,抱歉我的英语不好。
答案 0 :(得分:2)
您可以在SQl中使用modulo (%)
,就像这样
;with temp AS
(
SELECT *,
row_number() OVER(PARTITION BY OutletAsal ,OutletTujuan , Remark ,ExternalDocNo ORDER BY ic.Id) AS Rn
FROM ImportCsvDO ic
)
SELECT OutletAsal,
OutletTujuan,
Remark,
ExternalDocNo,
ROW_NUMBER() OVER(ORDER BY OutletAsal,OutletTujuan,Remark ASC) AS HeaderId,
t.Rn as GroupHeaderId
FROM temp t
WHERE t.Rn % 5 = 1
详细表格(假设您有标题表)
;with temp AS
(
SELECT *,
row_number() OVER(PARTITION BY OutletAsal ,OutletTujuan , Remark ,ExternalDocNo ORDER BY ic.Id) AS Rn
FROM @SampleData ic
)
SELECT t.ItemCode,
Qty,
ht.HeaderId AS HeaderID
FROM temp t
INNER JOIN @HeaderTable ht ON t.OutletAsal = ht.OutletAsal
AND t.OutletTujuan = ht.OutletTujuan
AND t.Remark = ht.remark
AND t.ExternalDocNo = ht.ExternalDocNo
AND (t.Rn - 1) / 5 = (ht.GroupHeaderId - 1) / 5
请参阅我的演示