Tra*_*nes 4 sql t-sql sql-server
我已经搜索了这个问题的答案,并发现了与我自己类似的问题,但是我没有“ColumnHeader”列来指示记录应进入哪个字段。前任:
因此,我的问题是 - 我有这种格式的数据(从产品推荐查询中选择为前 3 个结果):
------------------------------
CustID | StyleNo | Brand | ID
------------------------------
1 | ABC | BrandA| 1
------------------------------
1 | DEF | BrandB| 2
------------------------------
1 | GHI | BrandC| 3
------------------------------
2 | JKL | BrandA| 4
------------------------------
2 | MNO | BrandB| 5
------------------------------
2 | PQR | BrandD| 6
------------------------------
Run Code Online (Sandbox Code Playgroud)
我想让它看起来像这样:
-----------------------------------------------------------------
CustID | StyleNo1| StyleNo2| StyleNo3 | Brand1 | Brand2 | Brand3
-----------------------------------------------------------------
1 | ABC | DEF | GHI | BrandA | BrandB | BrandC
-----------------------------------------------------------------
2 | JKL | MNO | PQR | BrandA | BrandB | BrandD
-----------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
为了让我的程序能够简单地读取每个客户的推荐行。
我尝试过的是PIVOT- 但我没有什么可以真正总结的。我还尝试了Min(Case...When...Then...End)第二个链接问题中概述的内容,但如上所述,我没有引用“标题”列。
ID列暂时完全无关紧要,但它可能有助于解决这个问题。最终结果中不需要它。
我目前使用的是 SQLServer 2012
使用窗口函数 Row_Number() 和条件聚合
Select CustID
,StyleNo1 = max(case when RN=1 then StyleNo else null end)
,StyleNo2 = max(case when RN=2 then StyleNo else null end)
,StyleNo3 = max(case when RN=3 then StyleNo else null end)
,Brand1 = max(case when RN=1 then Brand else null end)
,Brand2 = max(case when RN=2 then Brand else null end)
,Brand3 = max(case when RN=3 then Brand else null end)
From (
Select *,RN = Row_Number() over (Partition By CustID Order by StyleNo,Brand)
From YourTable
) A
Where RN<=3
Group By CustID
Run Code Online (Sandbox Code Playgroud)
退货