2011-06-21 40 views
-3

可能重複:
convert one row into columns.如何使用PIVOT獲得所需結果

這是我的查詢。

DECLARE @temp TABLE 
(
MonthName   VARCHAR(10), 
[Year]    VARCHAR(10), 
StatusTypeId  INT, 
StatusTypeName  VARCHAR(50), 
StatusCount   INT 
) 

INSERT INTO @temp 
SELECT 
CONVERT(varchar(3), DATENAME(month, w.ExpectedStartDate)) as MonthName, 
datepart(yyyy, w.ExpectedStartDate) as [Year], 
w.StatusTypeId, 
st.StatusTypeName, 
COUNT(ISNULL(w.StatusTypeId, 0)) AS StatusCount 
FROM 
Worksheet w LEFT OUTER JOIN 
StatusType st ON st.StatusTypeId = w.StatusTypeId 
WHERE w.ProjectId = 20 
AND CONVERT(varchar(3), DATENAME(month, w.ExpectedStartDate)) between ('feb') AND  ('mar') 
GROUP BY 
datepart(yyyy, w.ExpectedStartDate), 
CONVERT(varchar(3), DATENAME(month, w.ExpectedStartDate)), 
w.StatusTypeId, 
st.StatusTypeName 

SELECT ISNULL(((CONVERT(VARCHAR(5), [Year])) + '-' + MonthName), 'Unknown') AS  MonthName, 
ISNULL(StatusTypeName, 'Unknown') AS StatusTypeName, 
StatusCount 
FROM @temp 

我想要這樣的結果。 enter image description here

請指導我。

謝謝。

回答