Sql 将两列分组进行透视

Sql Pivot By Grouping two columns

Sman Weekly Visit Party Wise

我在这里想要实现的是用相同的 LedId_Sman 和 LedId_Party 对行进行分组,然后在单个行中访问天数的旋转视图。

我的实际Table

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 的新手,所以深入了解它的工作原理将非常有帮助和赞赏。

您的数据中可能有额外的列,导致出现额外的行。使用数据透视表时,最好使用仅包含数据透视表中引用的列的子查询:

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