5

我正在使用 SQL Server 2008。

我有两张桌子

  1. User( UserID, Name, Link)
  2. 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 小提琴

我想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 等多个用户),否则使用标题字段作为列名。有可能这样做吗?干杯!

4

2 回答 2

2
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
于 2012-10-03T07:17:34.963 回答
1

这不是一个视图.. 这是一个将根据需要返回结果的过程

你可以称之为

proc_UserNotes 1
proc_UserNotes 2

ETC

CREATE procedure proc_UserNotes (@UserID int)
as
begin

DECLARE @cols AS NVARCHAR(MAX),
        @cols_WITH_MAX AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

select @cols_WITH_MAX = STUFF((SELECT distinct ',MAX(' 
              + QUOTENAME(Title) +') AS ' + QUOTENAME(Title)
                    from [UserNotes] where UserID =@UserID
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Title) 
                    from [UserNotes] where UserID =@UserID
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')        


set @query = 'SELECT [UserID], '+ @cols_WITH_MAX +' FROM(
             SELECT [UserID], ' + @cols + ' from 
            (
            SELECT * FROM 
            [UserNotes]   where UserID ='+cast(@UserID as varchar(20)) +'
            )X

            pivot 
            (
                MAX([Description])
                for [Title] in (' + @cols + ')
            ) p )a GROUP BY [UserID]'


print(@query)
execute(@query)

end 
于 2012-10-03T05:13:39.433 回答