sql - T-SQL 如何 "Flatten"前 3 行变成单行

标签 sql sql-server tsql

我搜索了这个问题的答案,发现了与我自己类似的问题,但是我没有“ColumnHeader”列来表示记录应该进入哪个字段。前任:

TSQL Pivot without aggregate function

trying to flatten rows into columns

Fetching Columns of a multiple rows in one row

因此,我的问题是 - 我有这种格式的数据(从产品推荐查询中选择为前 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 
 ------------------------------

我想让它看起来像这样:
 -----------------------------------------------------------------
 CustID | StyleNo1| StyleNo2| StyleNo3 | Brand1 | Brand2 | Brand3
 -----------------------------------------------------------------
    1   |   ABC   |   DEF   |   GHI    | BrandA | BrandB | BrandC 
 -----------------------------------------------------------------
    2   |   JKL   |   MNO   |   PQR    | BrandA | BrandB | BrandD
 -----------------------------------------------------------------

为了让我的程序简单地读取每个客户的推荐行。

我尝试的是一个 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

退货

enter image description here

关于sql - T-SQL 如何 "Flatten"前 3 行变成单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40750886/

相关文章:

sql - 近4季度数据

sql - 数据库事务是否会阻止竞争条件?

c# - Identity Column 的 Int32 限制

sql - 具有基于 GROUPING SETS 的数据集的展开-折叠报告

sql-server - 添加附加条件时出现 "No Join Predicate"- 为什么?

类似 "not having"的 SQL 查询?

mysql - 从两个表连接mysql

sql-server - 读取 DONE_IN_PROC

sql - 忽略 WHERE 过滤器转换为 float 时出错

sql - 汇总总计