SQL Server PIVOT 包含空值

问题描述 投票:0回答:1

我有一个数据透视查询,它在输出中返回空值。我一直在阅读MS文档,但我不明白为什么我在旋转输出中得到多行

内部查询如下:

select r.Casino, wf.WebsiteValue, dsf.Name, wf.DataStoreFieldId
from Review r 
inner join WebsiteField wf on wf.ReviewId = r.Id
inner join DataStoreField dsf on dsf.Id = wf.DataStoreFieldId 
where dsf.Id in (42, 43, 163) 
  and WebsiteValue like '%USD%'
  and Casino = 'Tusk Casino'

并返回以下内容:

Casino        WebsiteValue      Name                  DataStoreFieldId
------------ ------------- --------------------------------- ----------------
Tusk Casino   EUR/USD 16,000   Withdrawal per Month           42
Tusk Casino   EUR/USD 4,000    Withdrawal per Week            43
Tusk Casino   EUR/USD 1,000    Withdrawal Per Transaction     163

枢轴查询是:

select 
    Casino as 'Casino', 
    [42] as 'Withdrawal per Week', 
    [43] as 'Withdrawal per Month', 
    [163] as 'Withdrawal Per Transaction' 
from
    (select 
         r.Casino, wf.WebsiteValue, dsf.Name as FieldName, wf.DataStoreFieldId
     from 
         Review r 
     inner join 
         WebsiteField wf on wf.ReviewId = r.Id
     inner join 
         DataStoreField dsf on dsf.Id = wf.DataStoreFieldId 
     where 
         dsf.Id in (42, 43, 163) 
         and Casino = 'Tusk Casino' 
         and WebsiteValue like '%USD%') as source
pivot
    (MAX(WebsiteValue)  
     FOR DataStoreFieldId IN ([42], [43], [163])  
    ) AS PivotTable
where 
    Casino = 'Tusk Casino' 
order by 
    Casino

这将返回以下输出:

Casino       Withdrawal per Week  Withdrawal per Month  Withdrawal Per Transaction
------------ -------------------- --------------------- --------------------------
Tusk Casino  EUR/USD 16,000       NULL                  NULL
Tusk Casino  NULL                 NULL                  EUR/USD 1,000
Tusk Casino  NULL                 EUR/USD 4,000         NULL

如何消除 NULL 并将旋转后的输出作为一行返回?

sql sql-server pivot
1个回答
0
投票

问题是你内心的

SELECT
,你正在
SELECT
ing
dsf.Name
,并且由于该列既不在你的聚合函数中,也不在你的
IN
中,因此它(有效地)在你的
PIVOT
,因此每
 
GROUP BY 值都会得到一行 。如果您从内部
FieldName
中删除该列,那么它就会按您想要的方式工作。
当然,正如我在评论中所说,忘记 

SELECT

的存在;它是一个限制性运算符,我发现很多人都难以使用它或错误地使用它。相反,使用更简单、但限制也更少的条件聚合:

PIVOT

	
© www.soinside.com 2019 - 2024. All rights reserved.