【问题标题】:SQL Group By then put values n their own column in new recordSQL Group By 然后将值放在新记录中自己的列上
【发布时间】:2016-04-16 20:37:18
【问题描述】:

我正在尝试创建一个返回团队中球员的 SQL 视图。我已经得到了这样的返回结果。

Team      | Person
--------------------
Red Team  | Jack
Red Team  | Jill
Red Team  | Harry
Blue Team  | Bob
Blue Team  | Benny
Blue Team  | Brian

如何按团队分组并选择该团队中的每个人并将他们放入自己的列中?所以想要的结果应该是这样的。

Team       | Person | Person | Person |
---------------------------------------
Red Team   | Jack     Jill     Harry
Blue Team  | Bob      Benny    Brian

提前感谢您的帮助。

【问题讨论】:

  • 您使用的是哪个 DBMS?
  • 查找 pivot 和 unpibot

标签: c# sql sql-server pivot


【解决方案1】:

试试这个

为了识别每个人,我使用了row_number() 函数,然后在 case 语句中使用它们。

declare @tab table
(
    team varchar(50),
    Person varchar(50)
)

Insert into @tab
    values ('Red Team', 'Jack'),
            ('Red Team', 'Jill'),
            ('Red Team', 'Harry'),
            ('Blue Team', 'Bob'),
            ('Blue Team', 'Banny'),
            ('Blue Team', 'Brian')

SELECT 
    Team,
    MAX(case when PersonKey = 1 then Person end) Person,
    MAX(case when PersonKey = 2 then Person end) Person,
    MAX(case when PersonKey = 3 then Person end) Person
From 
(
        Select Team, 
         Person, 
         ROW_NUMBER() Over (Partition By team Order By Person) as PersonKey 
        From @tab
 ) t 
Group By Team

结果

Team        Person  Person  Person
----------------------------------
Blue Team   Banny   Bob     Brian
Red Team    Harry   Jack    Jill

【讨论】:

  • 谢谢。我现在试试
  • 你这个传奇,这就像一个魅力。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 2021-01-13
  • 2012-05-13
  • 2018-08-13
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多