title: How do I get distinct COUNT in dynamic pivot
body: <p>I have a temporay table #reservationWithBranch  contains</p>
  
  <pre><code>ScheduleName               UserId   BranchId        BranchCode
  NULL                        NULL    1              TVM
  XMS DAJ 20 Dec 2014          5      2              EKM
  XMS DAJ 20 Dec 2014          5      2              EKM
  XMS DAJ 29 Dec 2014          5      2              EKM
  XMS DAJ 29 Dec 2014          5      2              EKM
  NULL                         2      3              KDK
  XMS DAJ 29 Dec 2014          6      3              KDK
  XMS DAJ 20 Dec 2014          6      3              KDK
  NULL                         8      3              KDK
  NULL                         1      15             PLK
  NULL                         7      15             PLK
  NULL                        NULL    16             KNR
  NULL                         9      17             KA
  </code></pre>
  
  <p>The ScheduleName, UserId, BranchId and BranchCode are dynamic i want to get the output as follows</p>
  
  <pre><code>SheduleName        TVM  EKM  KDK PLK   KNR   KAK
  DAJ 20 Dec 2014     0   2    1    0     0    0
  DAJ 29 Dec 2014     0   2    1    0     0    0
  </code></pre>
  
  <p>I tried the following code</p>
  
  <pre><code>SELECT * from #reservationWithBranch
  --Prepare the PIVOT query using the dynamic 
  SET @DynamicPivotQuery = 
    N'SELECT ScheduleName, ' + @ColumnName + '
      FROM #reservationWithBranch
      PIVOT(COUNT(ScheduleName) 
            FOR BranchCode IN (' + @ColumnName + ')) AS PVTTable'
  
  
  
  --Execute the Dynamic Pivot Query
  EXEC sp_executesql @DynamicPivotQuery
  print @DynamicPivotQuery
  
  DROP TABLE #reservationWithBranch
  </code></pre>
  
  <p>But result is not correct. Can any one help me?</p>