1

这是我第一次尝试在 SQL 中进行动态旋转,但我有点卡住了!

我有两张要加入的表格,一张存放库存商品,另一张存放不同网站(来源)的库存商品的不同价格。由于可能有不同的站点,因此查询需要是动态的。

问题是我无法从结果中删除空值,我希望有人能提供帮助。

结果目前看起来像这样:

ID    site-site1   site-site2    site-site3
1      null          1.99          2.99
2      12.99         null          10.00
3      1.50          null          2.00

查询如下:

DECLARE @sources nvarchar(max)

SELECT @sources = 
STUFF(( SELECT DISTINCT ',[' + 
CASE 
WHEN ip.[Source] is null or ip.[Source] = '' THEN 'Default'
ELSE ip.[Source] 
END 
+ ' - ' +  
CASE 
WHEN ip.secondSource is null or ip.secondSource = '' THEN  'Default'
ELSE ip.secondSource 
END  
+ ']'
    FROM itemprice ip
    for XML PATH('')
  ), 1, 1, '')

DECLARE @SQL nvarchar(MAX)
SELECT @SQL = N'
SELECT *
FROM 
(
SELECT 
s.id, 
[Source] = CASE 
               WHEN ip.[Source] is null or ip.[Source] = '''' THEN  ''Default'' 
       ELSE ip.[Source] 
       END + '' - '' +  
CASE WHEN ip.secondSource is null or ip.secondSource = '''' THEN ''Default''
ELSE ip.secondSource 
END, 
    SalePrice = isnull(ip.SalePrice, 0)  
    FROM stock s 
    LEFT OUTER JOIN itemprice ip on ip.id = s.id
) data 
PIVOT 
( 
  MAX(SalePrice) for [Source] IN (' + @sources + ')
) as PivotTable
ORDER BY PivotTable.id'
exec sp_executesql @sql

任何帮助都将不胜感激,它似乎不像将每个 @sources 项目包装在 ISNULL 中那么简单。

谢谢

4

1 回答 1

2

不幸的是,您必须对每个单独的透视列进行 ISNULL。或者 CROSS JOIN 您的data子查询以生成完整的矩阵并在那里执行 ISNULL 。

例如,在透视列上使用 ISNULL 将 NULL 替换为 0:

DECLARE @sources nvarchar(max), @Selectlist nvarchar(max)

SELECT @sources = 
STUFF(( SELECT DISTINCT ',[' + 
CASE 
WHEN ip.[Source] is null or ip.[Source] = '' THEN 'Default'
ELSE ip.[Source] 
END 
+ ' - ' +  
CASE 
WHEN ip.secondSource is null or ip.secondSource = '' THEN  'Default'
ELSE ip.secondSource 
END  
+ ']'
    FROM itemprice ip
    for XML PATH('')
  ), 1, 1, '')

SELECT @Selectlist = 
STUFF(( SELECT DISTINCT ',ISNULL([' + 
CASE 
WHEN ip.[Source] is null or ip.[Source] = '' THEN 'Default'
ELSE ip.[Source] 
END 
+ ' - ' +  
CASE 
WHEN ip.secondSource is null or ip.secondSource = '' THEN  'Default'
ELSE ip.secondSource 
END  
+ '],0) [' + 
CASE 
WHEN ip.[Source] is null or ip.[Source] = '' THEN 'Default'
ELSE ip.[Source] 
END 
+ ' - ' +  
CASE 
WHEN ip.secondSource is null or ip.secondSource = '' THEN  'Default'
ELSE ip.secondSource 
END  
+ ']'
    FROM itemprice ip
    for XML PATH('')
  ), 1, 1, '')

DECLARE @SQL nvarchar(MAX)
SELECT @SQL = N'
SELECT ID, ' + @Selectlist + '
FROM 
(
SELECT 
s.id, 
[Source] = CASE 
               WHEN ip.[Source] is null or ip.[Source] = '''' THEN  ''Default'' 
       ELSE ip.[Source] 
       END + '' - '' +  
CASE WHEN ip.secondSource is null or ip.secondSource = '''' THEN ''Default''
ELSE ip.secondSource 
END, 
    SalePrice = isnull(ip.SalePrice, 0)  
    FROM stock s 
    LEFT OUTER JOIN itemprice ip on ip.id = s.id
) data 
PIVOT 
( 
  MAX(SalePrice) for [Source] IN (' + @sources + ')
) as PivotTable
ORDER BY PivotTable.id'
exec sp_executesql @sql
于 2012-10-19T10:29:03.387 回答