我对SQL Server PIVOT有点麻烦

时间:2013-10-31 06:28:09

标签: sql-server pivot max min

我对SQL Server查询有点麻烦。您可以在我的结果中看到,在第1级列中,有一个记录“1级活动”,但实际上有3个记录“1级活动,1级活动第二,1级活动第3”。使用我的命令MIN(activityName),它只显示1。

我想知道我们还有其他方法可以显示3条记录的数据吗?

SELECT 
   strandName as [Strand Name], 
   scopeName as [Scope Name], 
   FoundationLevel as [Foundation Level], 
   Level1 as [Level 1]
FROM 
    (select 
         st.strandName, s.scopeName, l.levelNo, activityName 
     from 
          strands as st 
     inner join 
          scopes as s on st.id = s.strandID 
     left join 
          activities as a on s.id = a.scopeID 
     left join 
          levels as l on a.levelID = l.id where unitID = 2) up 
PIVOT 
     (min(activityName) FOR levelNo IN (FoundationLevel, Level1)) AS pvt 
ORDER BY 
    scopeName

非常感谢。

1 个答案:

答案 0 :(得分:0)

WITH T
     AS (select strandName as [Strand Name] , scopeName as [Scope Name] , FoundationLevel as [Foundation Level] , Level1 as [Level 1]

FROM (select st.strandName, s.scopeName, l.levelNo, activityName from strands as st 

inner join scopes as s on st.id = s.strandID 

left join activities as a on s.id = a.scopeID 

left join levels as l on a.levelID = l.id where unitID = 2) 

SELECT *
FROM   T PIVOT (min(activityName)
FOR levelNo IN (Level 1 activity, Level 1 activity second, Level 1 activity third) ) AS pvt
ORDER  BY OrderID