Sql Pivot通过分组两列

时间:2016-09-13 11:09:17

标签: sql sql-server sql-server-2008-r2 pivot

Sman Weekly Visit Party Wise

我在这里要实现的是使用相同的LedId_Sman和LedId_Party对行进行分组,然后在一行中访问所访问的天数视图。

我的实际表格

LedId_Party LedId_Sman  VisitDay
----------- ----------- --------
426         296         3
426         296         6
441         296         2

查询我正在使用

SELECT LedId_Party, LedId_Sman,[1]as Sun,[2]as Mon,[3] as Tue,[4] as Wed,[5] as Thu,[6] as Fri,[7] as Sat
FROM dbo.tbl_WeeklyVisit

Pivot(
Count(VisitDay) 
For VisitDay in
([1],[2],[3],[4],[5],[6],[7]
))AS PiviotTable

这是我目前所获得的

LedId_Party LedId_Sman  Mon Tue Wed Thu Fri Sat Sun
        426       297   0   0   0   0   1   0   0
        426       297   0   1   0   0   0   0   0

这就是我想要的输出。

LedId_Party LedId_Sman  Mon Tue Wed Thu Fri Sat Sun
        426       297   0   1   0   0   1   0   0

我对SQL非常新,所以对它如何运作的见解会非常有帮助和赞赏。

1 个答案:

答案 0 :(得分:0)

您可能在数据中有额外的列,这些列会产生额外的行。使用数据透视表时,最好使用子查询,只包含数据透视表中引用的列:

SELECT LedId_Party, LedId_Sman, [1] as Sun,[2] as Mon, [3] as Tue,
       [4] as Wed, [5] as Thu, [6] as Fri, [7] as Sat
FROM (SELECT LedId_Party, LedId_Sman, VisitDay
      FROM dbo.tbl_WeeklyVisit
     ) wv
PIVOT(Count(VisitDay) 
      For VisitDay in ([1], [2], [3], [4], [5], [6], [7]
                      )
     ) as PiviotTable