将不同的值分隔到列中

Separate distinct values in to columns

大家好,我是 SQL 的新手。我有一个 table (TABLE1),其中包含如下两列

Name age
--------
jim  18
jim  21
dave 18
dave 18
john 23
john 41

我需要在 SSMS 中创建一个视图,在单独的列中列出每个名字的不同年龄,如下所示

Jim  Dave  John
---------------
18   18     23
21          41

我试过像

这样的子查询

SELECT DISTINCT AGE FROM TABLE1 WHERE NAME = JIM

但是我遇到了一个子查询不能return多个值。

您可以使用 row_number() 并进行聚合:

select max(case when name = 'jim' then age end) as jim,
       max(case when name = 'dave' then age end) as dave,
       max(case when name = 'john' then age end) as john
from (select t.*, row_number() over (partition by name order by age) as seq
      from table t
     ) t
group by seq;