有关PIVOT处理空值问题
各位大神请看:
pivot IsNull Null
CREATE TABLE #Table_Stock(
GoodId INT,
Qty INT,
QtyOut INT,
StoreName VARCHAR(32)
)
CREATE TABLE #Table_Goods(
GoodId int,
Title VARCHAR(126)
)
INSERT INTO #Table_Stock ( GoodId, Qty, QtyOut, StoreName )
SELECT 1,10,0,'总仓' UNION
SELECT 1,0,0,'分仓' UNION
SELECT 2,5,1,'总仓'
INSERT INTO #Table_Goods ( GoodId, Title )
SELECT 1,'A1' UNION
SELECT 2,'B2'
;WITH Stocks AS (
SELECT a.Title,StoreName ,'总库存:'+CONVERT(VARCHAR,b.Qty)+' 在单量:'+CONVERT(VARCHAR,b.QtyOut) QtyDetail
FROM #Table_Goods a LEFT JOIN #Table_Stock b ON a.GoodId = b.GoodId
)
SELECT * FROM Stocks
PIVOT (max(QtyDetail) for StoreName in (总仓,分仓)) pv
CREATE TABLE #Table_Stock(
GoodId INT,
Qty INT,
QtyOut INT,
StoreName VARCHAR(10)
)
CREATE TABLE #Table_Goods(
GoodId int,
Title VARCHAR(10)
)
INSERT INTO #Table_Stock(GoodId, Qty, QtyOut, StoreName)
SELECT 1,10,0,'总仓' UNION
SELECT 1,0,0,'分仓' UNION
SELECT 2,5,1,'总仓'
INSERT INTO #Table_Goods(GoodId, Title)
SELECT 1,'A1' UNION
SELECT 2,'B2'
;WITH Stocks AS (
SELECT a.Title,
b.StoreName,
'总库存:'+CONVERT(VARCHAR,b.Qty)+' 在单量:'+CONVERT(VARCHAR,b.QtyOut) 'QtyDetail'
FROM #Table_Goods a
LEFT JOIN #Table_Stock b ON a.GoodId = b.GoodId
)
SELECT Title,
总仓,
isnull(分仓,'总库存:0 在单量:0') '分仓'
FROM Stocks
PIVOT(max(QtyDetail) for StoreName in (总仓,分仓)) pv
/*
Title 总仓 分仓
---------- ---------------------- ----------------------
A1 总库存:10 在单量:0 总库存:0 在单量:0
B2 总库存:5 在单量:1 总库存:0 在单量:0
(2 row(s) affected)
*/