27,579
社区成员
发帖
与我相关
我的任务
分享
CREATE TABLE tb
(
ID CHAR(10)
,Month1qty INT
,Month2qty INT
,Month3qty INT
,Month4qty INT
,Month5qty INT
,Month6qty INT
)
INSERT INTO tb
SELECT 'F000000E24',55,30,45,NULL,NULL ,60
SELECT * FROM tb
SELECT ID
,timeperiod
,val AS performance
FROM tb
UNPIVOT (val FOR timeperiod IN (Month1qty,Month2qty,Month3qty,Month4qty,Month5qty,Month6qty)) AS x
--结果
ID timeperiod performance
---------- ------------------ -----------
F000000E24 Month1qty 55
F000000E24 Month2qty 30
F000000E24 Month3qty 45
F000000E24 Month6qty 60
(4 row(s) affected)
如何将Month4qty,Month5qty在结果中也显示出来,且performance的值显示为NULL .
drop table tb
go
CREATE TABLE tb
(
ID CHAR(10)
,Month1qty INT
,Month2qty INT
,Month3qty INT
,Month4qty INT
,Month5qty INT
,Month6qty INT
)
INSERT INTO tb
SELECT 'F000000E24',55,30,45,NULL,NULL ,60
select ID,
timeperiod,
case when performance=0 then null else performance end performance
from (
SELECT ID
,timeperiod
,val AS performance
FROM (select ID,
isnull(Month1qty,0)Month1qty,
isnull(Month2qty,0)Month2qty,
isnull(Month3qty,0)Month3qty,
isnull(Month4qty,0)Month4qty,
isnull(Month5qty,0)Month5qty,
isnull(Month6qty,0)Month6qty
from tb)tb
UNPIVOT (val FOR timeperiod IN (Month1qty,Month2qty,Month3qty,Month4qty,Month5qty,Month6qty)) AS x)
t
/*
ID timeperiod performance
---------- -------------------------------------------------------------------------------------------------------------------------------- -----------
F000000E24 Month1qty 55
F000000E24 Month2qty 30
F000000E24 Month3qty 45
F000000E24 Month4qty NULL
F000000E24 Month5qty NULL
F000000E24 Month6qty 60
(6 個資料列受到影響)
*/
--try
isnull(lie,'null')
/*
ID timeperiod performance
---------- -------------------------------------------------------------------------------------------------------------------------------- -----------
F000000E24 Month1qty 55
F000000E24 Month2qty 30
F000000E24 Month3qty 45
F000000E24 Month4qty 0
F000000E24 Month5qty 0
F000000E24 Month6qty 60
(6 個資料列受到影響)
*/
SELECT ID
,timeperiod
,val AS performance
FROM (select ID,
isnull(Month1qty,0)Month1qty,
isnull(Month2qty,0)Month2qty,
isnull(Month3qty,0)Month3qty,
isnull(Month4qty,0)Month4qty,
isnull(Month5qty,0)Month5qty,
isnull(Month6qty,0)Month6qty
from tb)tb
UNPIVOT (val FOR timeperiod IN (Month1qty,Month2qty,Month3qty,Month4qty,Month5qty,Month6qty)) AS x