这是我第一次尝试在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
任何帮助都会非常感激,看起来好像不像在ISNULL中包装每个@sources项一样简单。
由于
答案 0 :(得分:2)
不幸的是,您必须在每个单独的透视列中使用ISNULL。或者CROSS JOIN您的data
子查询以生成完整矩阵并在那里执行ISNULL。
e.g。在透视列上使用ISNULL将0替换为NULL:
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