SQL 数据透视表 Table 动态 - 排除未使用的列

SQL Pivot Table Dynamic - exclude unused columns

我有以下 SQL 代码创建了一个非常有用的枢轴 table:

Use [A1_20132014]

DECLARE @cols NVARCHAR (MAX)

SELECT @cols = COALESCE (@cols + ',[' + Link_ID + ']', '[' + Link_ID + ']')
               FROM    (SELECT DISTINCT Link_ID FROM A1) PV  
               ORDER BY Link_ID

DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT * FROM 
             (
                 -- We will select the data that has to be shown for pivoting
                 SELECT date_1, StartHour,Cost, Link_ID
                 FROM A1
                 WHERE Section = (''1AB'')
             ) x
             PIVOT 
             (
                 -- Values in each dynamic column
                 SUM(Cost)
                 -- Select columns from @cols 
                 FOR Link_ID IN (' + @cols + ')                      
            ) p;' 

EXEC SP_EXECUTESQL @query

来自这些标题

       link_id       Section   date_1     StartHour   Cost    data_source
   4000000027866016A   8NB    2013-09-02    6         5871        1
   4000000027866017B   5EB    2013-10-09    9         8965        2
   4000000027856512B   4TB    2013-05-06    15        6754        1
   4000000027866015A   6HB    2013-06-08    8         5354        1
   4000000027866011A   1AB    2013-06-09    11          2         1

使用这些来源类型;

    link_Id         nvarchar(50)    
    Section         nvarchar(50)    
    Date_1          smalldatetime   
    StartHour       int 
    Cost            float    
    data_source     int

然而,尽管 WHERE 子句指定了某个部分,但不幸的是,所有部分仍然出现在数据透视中 table,但一直向下填充 NULL 值。

有没有办法完全排除不满足WHERE子句的列?

感谢您的帮助。

亨利。

将where 子句放在子查询中。这样你只会得到适用于 1AB

的列
SELECT @cols = COALESCE (@cols + ',[' + Link_ID + ']', '[' + Link_ID + ']')
               FROM    (SELECT DISTINCT Link_ID FROM A1 WHERE Section = '1AB') PV  
               ORDER BY Link_ID