使用SQL PIVOT和JOINS

时间:2016-01-05 07:03:23

标签: sql-server

我编写了以下查询,产生以下输出:

SELECT 
users.user_id AS 'User ID', 
users.first_name AS 'First Name', 
users.last_name AS 'Surname', 
users.login AS 'Username', 
CASE users.type WHEN 0 THEN 'Student' WHEN 1 THEN 'Staff Member' WHEN 2 THEN 'Guest / Other' END AS 'User Type', 
CASE users.active WHEN 1 THEN 'Active' ELSE 'Inactive' END AS 'User Status', campuses.campus_name AS 'Campus', users.year_level AS 'Year Level', 
users.class AS 'Class', 
CASE users.eligible WHEN 1 THEN 'Yes' ELSE 'No' END AS 'Eligible', 
forms.form_title AS 'Form Name', 
users_forms_map.date AS 'Date Returned' 

FROM users_forms_map 
INNER JOIN users ON users_forms_map.user_fk = users.pk 
INNER JOIN campuses ON users.campus_id=campuses.campus_id 
INNER JOIN forms ON users_forms_map.form_id=forms.form_id

enter image description here

我想PIVOT这个表为每个'表格名称'创建一个列。每个用户一行。 '表格名称'因为没有有限的表格名称,所以需要是动态的。

如果我希望实现的目标是可能的,那么会产生以下结果: enter image description here

我一直在努力做到这一点!提前感谢您提供的任何指导。

2 个答案:

答案 0 :(得分:0)

如果您可以执行多个步骤,请尝试以下

create table #form
(
userid int,
name varchar(50),
surname varchar(50),
username varchar(50),
type   varchar(50),
userstatus varchar(50),
campus   varchar(50),
level  int ,
class  varchar(1),
eligible varchar(5),
formname varchar(50),
datereturned datetime
)

insert into #form
values
(123, 'thomas', 'pagram', 'tpar2', 'staff member', 'active', 'primary campus',
 0, '', 'yes', 'participation form', '2015-12-29')


insert into #form
values
(123,  'thomas', 'pagram', 'tpar2', 'staff member', 'active', 'primary campus',
 0, '', 'yes', 'one2one contract', '2016-01-01')



 --drop table #form1


 select userid, name, surname, username, type, userstatus, campus, level, class,eligible,
 cast ( '' as date) [participation form] , cast ( '' as date) [one2one contract]
 into #form1
 from #form
 group by userid, name, surname, username, type, userstatus, campus, level, class,eligible


 update f1
 set [participation form] = f.datereturned
 from #form1 f1
 join #form f
 on (f.userid = f1.userid)
 where f.formname = 'participation form'

  update f1
 set [one2one contract] = datereturned
 from #form1 f1
 join #form f
 on (f.userid = f1.userid)
 where f.formname = 'one2one contract'


userid name    surname  username    type            userstatus  campus      level  class       eligible     participation form  one2one contract
123    thomas  pagram   tpar2       staff member    active      primary    campus   0           yes         2015-12-29          2016-01-01 

答案 1 :(得分:0)

最有效的解决方案是在应用程序本身内处理这种逻辑。没有使用服务器端SQL解决方案。