存储过程(SQL SERVER 2008中的动态列)

时间:2011-10-20 06:51:54

标签: sql-server-2008 stored-procedures

我有3个表Project departmentsprojectStatus

  

ID          Name
1         Software
2           XML1
.            .
.            .
  

项目

ID       Name        DeptID   StatusID
1        Prj1           1        1
2        prj2           2        2
.         .             .        .
.         .             .        .
  

projectStatus

ID      Name
1       InProgress
2       Pending
.         .
.         .

我想要下面的组合:
enter image description here

我试过这个

SELECT 
    Status=[Name],
    Software=(
        SELECT COUNT(*)
        FROM Projects 
        WHERE StatusID=PS.ID and DeptI =1
    ),
    XML1=( 
        SELECT COUNT(*)
        FROM Projects
        WHERE CurrentStatusID=PS.ID and DeptID=2
    ),
    Imaging=(
        SELECT COUNT(*)
        FROM Projects
        WHERE CurrentStatusID=PS.ID and DeptID =3
    )  
FROM
    [MIS_STORE].[dbo].[M_ProjectStatuses] PS   

在这里,我希望根据部门数量动态检索列数。 提前谢谢......

修改:溶液

DECLARE @cols NVARCHAR(2000);
DECLARE @query NVARCHAR(4000);


SELECT  @cols = COALESCE(@cols + ',[' + Name + ']',
                         '[' + Name + ']')
FROM    M_Departments 
ORDER BY Name


SET @query = 'SELECT [Status], '+
@cols +'
FROM
(SELECT Projects.Name, 
M_Departments.Name AS dept, 
M_ProjectStatuses.Name AS [Status]
FROM     Projects INNER JOIN
         M_Departments ON Projects.M_DeptID = M_Departments.ID INNER JOIN
         M_ProjectStatuses ON Projects.CurrentStatusID = M_ProjectStatuses.ID) test
 PIVOT
(
count(name)
FOR dept IN
( '+ @cols +')) p '
EXECUTE(@query)

1 个答案:

答案 0 :(得分:0)

我有关于此的精彩帖子。 I referred this link