如何使用PIVOT获得所需的结果

时间:2011-06-21 08:58:51

标签: sql sql-server sql-server-2005

  

可能重复:
  convert one row into columns.

这是我的疑问。

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

请指导我。

感谢。

1 个答案:

答案 0 :(得分:1)

例如

select
  *
from
(
  select
    monthname,statustypename
  from yourtable
) DataTable
PIVOT
(
  SUM(statuscount)
  FOR statustypename
  IN ( 
    [tobescheduled],[complete]
  )
) PivotTable

同时检查链接 http://geekswithblogs.net/lorint/archive/2006/08/04/87166.aspx