Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server MSSQL连接表w位_Sql Server_Sql Server 2008_Join_Pivot_Sqlfiddle - Fatal编程技术网

Sql server MSSQL连接表w位

Sql server MSSQL连接表w位,sql-server,sql-server-2008,join,pivot,sqlfiddle,Sql Server,Sql Server 2008,Join,Pivot,Sqlfiddle,我有三张桌子: 1) 用户表 UserId UserName 1 Mike 2 John 3 Jennifer 2) FormName fID fName 1 edit 2 cafe 3 backoffice 3) 用户到表单 fId UserId Allowed(bit) 1 1 0 2 1 1 3 1 1 2 2

我有三张桌子: 1) 用户表

UserId UserName 
  1      Mike
  2      John
  3      Jennifer
2) FormName

fID   fName
 1     edit
 2     cafe
 3     backoffice
3) 用户到表单

fId  UserId   Allowed(bit)
 1     1         0
 2     1         1
 3     1         1
 2     2         1 
 3     2         0
第一个表是包含用户信息的用户表。 第二个表是表单表,用于存储应用程序的表单名称 第三个表是用户级表,其中说明允许哪个用户打开哪个表单

我想创建sql查询,在该查询中,我可以在单个表中查看所有信息,如:

UserId USerName   Edit  Cafe BackOffice
  1      mike      0     1      1  
  2      john      1     1      0

我认为使用SQL Fiddle和Pivot是可行的,但我很难找出正确的代码。

您可以使用Pivot函数,但您必须将
允许的
列转换为
数据类型以外的内容。例如,下面的命令将其强制转换为
int

select userid, username,
  coalesce(Edit, 0) Edit, 
  coalesce(Cafe, 0) Cafe, 
  coalesce(BackOffice, 0)  BackOffice
from
(
  select u.userid, 
    u.username, 
    f.fname, 
    cast(allowed as int) allowed
  from usertable u
  inner join user_form uf
    on u.userid = uf.userid
  inner join formname f
    on uf.fid = f.fid
) d
pivot
(
  max(allowed)
  for fname in (Edit, Cafe, BackOffice)
) piv;