在哪里使用isnull函数

时间:2015-10-28 21:58:37

标签: sql-server pivot isnull

我正在为报告使用动态数据透视表脚本。以下是我的剧本。

> dat2[1,2] <- 2   
> dat2[2,2] <-2; dat2[3,2]<-2; dat2[4,2]<-4
>  mod <-  lm( res ~ A+B, dat2) 
>  summary(mod)

Call:
lm(formula = res ~ A + B, data = dat2)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.42819 -0.59241 -0.04483  0.62482  2.12461 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)  
(Intercept)  0.11165    0.05768   1.936   0.0532 .
A2          -0.67213    0.91201  -0.737   0.4613  
A3          -1.51763    1.17803  -1.288   0.1980  
A4          -0.97195    1.17710  -0.826   0.4092  
B2           0.62320    0.91196   0.683   0.4945  
B3           1.52500    1.17520   1.298   0.1947  
B4           0.92448    1.17520   0.787   0.4317  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.9102 on 993 degrees of freedom
Multiple R-squared:  0.002753,  Adjusted R-squared:  -0.003272 
F-statistic: 0.4569 on 6 and 993 DF,  p-value: 0.8403
#--------------
> library(rms)

> vif(mod)
      A2       A3       A4       B2       B3       B4 
192.6898 312.4128 308.5177 191.2080 312.5856 307.5242 

将是我的isnull函数,因此将零替换为null。 请指教!!

这是我的新版Print @SQL

   DECLARE @Columns VARCHAR(MAX)
set @Columns= ''

SELECT @Columns = @Columns + (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender 
WHERE 1=1 
AND CAST(dates AS DATETIME) >= DATEADD(mm, -35 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)) 
AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)

SET @Columns = LEFT(@Columns, LEN(@Columns) - 1)

DECLARE @SQL NVARCHAR(MAX) 
set @SQL= ''
SET @SQL =
'WITH BaseData AS
(
     select 
        vendor_code,
        RTRIM(LTRIM(cast(datename(month, [CLOSED_DATE]) as char(15))))+'','' + RTRIM(LTRIM(cast(year([CLOSED_DATE]) as char(20)))) as [CLOSED_DATE],
        count(vendor_code) as [No. of Case] 
   from #teamp t WITH (NOLOCK)
      where 
       [CLOSED_DATE] is not null
  group by 
       vendor_code, CLOSED_DATE
)   
SELECT * 
FROM BaseData
PIVOT
(
    sum([No. of Case])
    FOR CLOSED_DATE IN (' +  @Columns + ')
) AS PivotTable'

EXECUTE sp_executesql @SQL

这是我的新版Print @SQL

1 个答案:

答案 0 :(得分:2)

您需要声明另一个变量:

DECLARE @Columns2 VARCHAR(MAX) = ''

然后做主要的事情:

SELECT @Columns2 = @Columns2 + 'ISNULL(' + (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ', 0) AS ' + (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender 
WHERE 1=1 
AND CAST(dates AS DATETIME) >= DATEADD(mm, -35 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)) 
AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)

SET @Columns2 = LEFT(@Columns2, LEN(@Columns2) - 1)

然后使用它:

...
SELECT ' + @Columns2 + '
FROM BaseData
PIVOT
...