我有3个表Project
departments
和projectStatus
系
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
. .
. .
我想要下面的组合:
我试过这个
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)