SQL中的交叉表(Pivot)查询

时间:2012-06-24 12:43:04

标签: sql-server-2008 pivot-table

我在SQL中使用了一个数据透视查询,如下所示:

   SELECT  classification, [BSL] AS BSL, [AQ] AS AQ, [KYN] AS KYN,  ([BSL] + [AQ] + 
   [KYN]) AS CR_TTL
   FROM 
  ( 
   SELECT classification, Shed 
   FROM PunctualityMain WHERE Date >= '4/1/2012' AND Date <= '6/30/2012'   
  ) x
  PIVOT 
 ( 
  COUNT(Shed) 
  FOR Shed IN ([BSL],  [AQ],  [KYN]))  p  ">

结果我在空单元格中得到0,是否可以在结果页面中显示null代替0?

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是使用NULLIF快捷方式,如下所示:

SELECT  classification
, NULLIF([BSL],0) AS BSL
, NULLIF([AQ],0) AS AQ
, NULLIF([KYN],0) AS KYN
, NULLIF([BSL] + [AQ] + [KYN],0) AS CR_TTL 
       FROM  
      (  
       SELECT classification, Shed  
       FROM PunctualityMain WHERE Date >= '4/1/2012' AND Date <= '6/30/2012'    
      ) x 
      PIVOT  
     (  
      COUNT(Shed)  
      FOR Shed IN ([BSL],  [AQ],  [KYN]))  p