用于列的不同关键字,更改该列的值的顺序,会影响数据透视表

问题描述 投票:-1回答:2
SELECT **@COLS** = STUFF((SELECT DISTINCT ',' + QUOTENAME(BR.EMPLOYEENAME) FROM **#TMP_RESULTS** BR  FOR XML PATH('')),1,1,''); 

SET @QUERY = 'INSERT INTO #RESULTS SELECT DISTINCT P.EMP_ID,'+**@COLS**+' FROM     
      (                  
      SELECT EMP_ID,EMPLOYEENAME,OFFICE_ID,VALUE FROM **#TMP_RESULTS** BR) AS X    
      PIVOT     
      (    
       MAX( X.VALUE)    
       FOR X.EMPLOYEENAME IN (' + **@COLS** + ')    
      ) AS P '; 
sql-server pivot-table distinct
2个回答
0
投票

这里EmployeeName是Column,其值在Pivoted时成为列标题。 @COLSEmployeeName列上使用Distinct关键字,因为选择的EmployeeNames的顺序将会改变。在SQL中使用数据透视表时,它期望@COLS(即列标题/ EmployeeName)与TMP_RESULTS源表中的顺序相同。但@COLS有不同的EmployeeNames顺序。因此,我们在#RESULTS表中得到了不希望的结果。也就是说,列标题与值互换。要解决这个问题,我们可以在ID上使用Distinct和group by,或者我们可以删除Distinct关键字并将来自xml路径的不同列标题添加到虚拟表中,并且因为TMP_RESULTS表中也会使用相同的顺序,所以不会旋转交换结果。


0
投票

@COLS从TEMPPARAMETERS而不是TMP_RESUTLS中获取值。

TMP_RESULTS has mutiple Values for each of the EmployeeNames. The EmployeeNames are in proper order, as sent in XML. Both TEMPPARAMETERS and TMP_RESUTLS have the same order of EmployeeNames. TEMPPARAMETERS has distinct EmployeeNames initially taken from XML. Using 'Distinct' again on it, will change the order of EmployeeNames which is being added to @COLS. Now @COLS and TMP_RESUTLS's EmployeeNames orders are different. Hence using @COLS as headers and MAX(Values) of TMP_RESUTLS, will interchange the results in the columns. Meaning Distinct is changing the order of columns, which has a bad impact on Pivot table results.

© www.soinside.com 2019 - 2024. All rights reserved.