簡體   English   中英

sql基於組記錄的前1個

[英]sql top 1 based on group records

ProductMst (組合是唯一的-CodeNum,MainCatid,SubCatid)

id  CodeNum     MainCatid   SubCatid    Desc        Qty
1   001         1           1           prod1       5
2   001         1           2           prod2       10
3   001         2           3           prod3       1
4   002         2           3           prod4       2
5   003         2           3           prod5       3
6   004         1           1           prod6       4

子表SubCatMst

id  name    subcode
1   scat1   00
2   scat2   00
3   scat3   02
4   scat4   03

所需結果

id  CodeNum     MainCatid   SubCatid    Desc        Qty     subcode
2   001         1           2           prod2       15      00
3   001         2           3           prod3       1       02
4   002         2           3           prod4       2       02
5   003         2           3           prod5       3       02
6   004         1           1           prod6       4       00

基本上,我想將subcode分組(如果相同)並根據subcode sum (Qty) 並且,將TOP 1記錄數據作為基於MAX(Qty)所有列。

摘要:請檢查合並的前2條記錄。

查詢嘗試:

select * from (
select A.*, B.subcode, 
ROW_NUMBER() OVER( PARTITION BY A.CodeNum, A.MainCatid, B.subcode ORDER BY A.Qty desc) as row 
from ProductMst A 
inner join SubCatMst B on A.SubCatid=B.id
) as A where row<=1

您的問題是:

我想將子代碼分組

如果是一樣的話? 我認為這意味着如果codenum相同。

不管確切的字段是什么,邏輯都是相同的。 您可以使用窗口函數來匯總數據並確定要選擇的行:

select ps.*
from (select p.*, sc.subcode,
             sum(qty) over (partition by codenum, subcode) as qty,
             row_number() over (partition by codenum, subcode order by qty desc) as seqnum
      from ProductMst p join
           SubCatMst sc
           on p.subcatid = sc.id
     ) ps
where seqnum = 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM