如何在没有聚合的情况下编写SQL pivot

如何在没有聚合的情况下编写SQL pivot,sql,sql-server,Sql,Sql Server,你能帮我写下下面输出的SQL语句吗 您可以使用行编号()执行聚合: select name, max(case when seq = 1 then colors end) as color1, max(case when seq = 2 then colors end) as color2 from(select t.*, row_number() over (partition by name order by colors) as seq from t

你能帮我写下下面输出的SQL语句吗


您可以使用
行编号()
执行聚合:

select name, 
       max(case when seq = 1 then colors end) as color1,
       max(case when seq = 2 then colors end) as color2
from(select t.*, row_number() over (partition by name order by colors) as seq
     from table t
    ) t
group by name;
编辑:如果不想进行聚合,则可以使用
CTE

with cte as (
     select t.*, row_number() over (partition by t.name order by t.color) as seq
     from table t
)
select distinct c.name, c1.color as color1, c2.color as color2
from cte c inner join
     cte c1
     on c1.name = c.name and c1.seq = 1 inner join
     cte c2
     on c2.name = c.name and c2.seq = 2;
你可以试试这个

DECLARE @TableA TABLE (Name VARCHAR(10), Colors VARCHAR(10))

INSERT INTO @TableA 
VALUES
('Betty', 'Pink'),
('Betty', 'Blue'),
('Jug', 'Purple'),
('Jug', 'White')

SELECT Name, [1] AS Color1, [2] AS Color2 FROM (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Name) AS RN 
    FROM @TableA 
) SRC PIVOT (MAX(Colors) FOR RN IN ([1],[2]) ) PVT
结果:

Name       Color1     Color2
---------- ---------- ----------
Betty      Pink       Blue
Jug        Purple     White

SQL表没有顺序。因此,除了显式逻辑之外,没有办法将列按特定顺序排列

因此,我建议只使用聚合:

select name, min(color) as color1, max(color) as color2
from tablea
group by name;

这不会以与您拥有的列相同的顺序返回这些列。但是,数据中没有指定排序,因此我不理解您是如何定义它的。

您能解释一下为什么使用此行号()吗?我也不使用此行号获取结果。。你能帮我理解一下吗。@user11894930。如果不使用
行编号
,则需要指定可能很难使用的颜色名称。因此,通过使用
rownumber
我们可以轻松获得颜色名称。谢谢Serkan Arslan