将结果拆分为单独的列

时间:2013-08-01 11:16:25

标签: sql sql-server sql-view sql-server-2008r2-express

我需要一个与视图兼容的SQL查询来完成以下结果(视图1)。

Table 1:
--------------
ID |    Folder
--------------
1  |    foo
2  |    bar

Table 2:
-------------------------------------
ID |    Table1_ID | Name    |   Right
-------------------------------------
1  |    1         | fooUser |   W
2  |    2         | barUser |   R

View 1:
-------------------------------
Folder  |   fooUser  |  barUser
-------------------------------
foo     |     W      |
bar     |            |    R

我只能使用自定义函数执行此操作,但我只能将其用作存储过程。我想将结果绑定到GridView。 我希望有人可以帮助我。

3 个答案:

答案 0 :(得分:2)

只要您想将值转换为列,请使用PIVOT。在这里你需要一个选择:

SELECT Folder, [fooUser], [baruser]
FROM (SELECT t.Folder, tt.* FROM one t JOIN two tt ON t.ID = tt.Table1_ID) AS source
PIVOT
(
  MAX(Rightt)
  FOR Name IN (fooUser, barUser)
) AS PivotTable;

将其应用于CREATE VIEW ... AS,它应该有效。

<强> SQLFiddle

答案 1 :(得分:2)

您可以使用带有CASE表达式的聚合函数将数据从行转移到列中:

select t1.folder,
  max(case when t2.name = 'fooUser' then [right] else '' end) fooUser,
  max(case when t2.name = 'barUser' then [right] else '' end) barUser
from table1 t1
inner join table2 t2
  on t1.id = t2.Table1_ID
group by t1.folder;

请参阅SQL Fiddle with Demo

如果您需要动态解决方案,则需要使用动态SQL:

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Name) 
                    from table2
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT folder, ' + @cols + ' 
            from 
            (
              select t1.folder,
                t2.name, t2.[right]
              from table1 t1
              inner join table2 t2
                on t1.id = t2.Table1_ID
            ) x
            pivot 
            (
                max([right])
                for name in (' + @cols + ')
            ) p '

execute(@query);

请参阅SQL Fiddle with Demo

答案 2 :(得分:0)

只是为了好玩,这是一个愚蠢的答案,但它确实有效:)我建议使用PIVOT @makciook。

select a.Folder,
       foo.[Right] fooUser,
       bar.[Right] barUser
  from one a
  left join two foo on a.ID = 1 and foo.ID = 1
  left join two bar on a.ID = 2 and bar.ID = 2