sql - T-SQL 枢轴 : One row to column name and the other to value

标签 sql sql-server-2008 pivot pivot-table

我正在使用 SQL Server 2008。

我有两张 table

  • User ( UserID, Name, Link )
  • UserNotes ( NoteID, UserID, Title, Description )

  • 这是示例数据结构。
    INSERT INTO [User]
        ([UserID], [Name], [Link])
    VALUES
        (1, 'John', 'L1'),
        (2, 'Steve', 'L234');
    
    INSERT INTO [UserNotes]
        ([NoteID], [UserID], [Title], [Description])
    VALUES
        (1, 1, 'AboutJohn', 'This is about john'),
        (2, 1, 'John Work', 'This is where John work'),
        (3, 1, 'John Education', 'This is the uni where John go'),
        (4, 2, 'Steve Note1', 'Des1 about Steve'),
        (5, 2, 'Steve Note2', 'Des2 about Steve');
    

    这是SQL Fiddle

    我想按如下方式创建 View ( User_view ),当我执行此命令时,输出应如下所示。
    SELECT * FROM User_view WHERE UserID IN (1)
    
    UserID    Name   AboutJOhn              JohnWork                  JohnEducation
    1         John   This is about john     This is where Johnwork    This is the uni where John go
    
    Title子表的列应该成为列名和 Description应该成为该列的值,我们不知道我们将有多少行。当我们选择两个用户以及使用哪个名称的列名时,我意识到了这个问题。在这种情况下,我们可以使用(Note1、Note2、Note3 等用于多个用户),否则使用标题字段作为列名。有可能这样做吗?干杯!

    最佳答案

    CREATE VIEW User_view
    AS
    SELECT UserID, Name, [AboutJohn], [John Work], [John Education]
    FROM 
     (
      SELECT n.UserID, u.Name, n.Title, n.Description
      FROM [User] u JOIN UserNotes n ON u.UserID = n.UserID
      WHERE u.UserID IN (1)
      ) a
    PIVOT
     (
      MAX(Description)
      FOR Title IN ([AboutJohn], [John Work], [John Education])
      ) b
    

    关于sql - T-SQL 枢轴 : One row to column name and the other to value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12701872/

    相关文章:

    sql - 获取一周中某一天的时间戳

    SQL Server 条件 CHECK 约束

    php - Laravel,与多个模型的多对多关系

    python - 如何使用python计算数据透视表

    mysql - 哪里有 SQL 子查询

    sql - Microsoft SQL Server 备份文件非常重

    SQL Server有没有办法绕过重复的条件行

    sql - 有没有一种方法可以将多个更新查询合并到一个查询中?

    SQL Server 在新表中使用透视/逆透视

    python - 查找两个日期之间的日期范围并重复列