2

我需要一个视图兼容的 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。我希望有人可以帮助我。

4

3 回答 3

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

于 2013-08-01T12:52:13.537 回答
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

于 2013-08-01T14:10:21.053 回答
0

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

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
于 2013-08-01T14:05:25.393 回答