简体   繁体   English

SQL Server 2008-数据透视表ISNULL = 0不起作用

[英]SQL Server 2008 - Pivot Table ISNULL = 0 Not working

I am working on joining two tables and display the result in pivot table. 我正在联接两个表,并在数据透视表中显示结果。 This is my first time doing the pivot, so I am still very new to this. 这是我第一次进行数据透视,因此我对此还很陌生。

I have this query below is display the result almost I what I want, but one small thing I couldn't figure out. 我在下面有这个查询,它显示的结果几乎是我想要的,但是我无法弄清楚一件事。 if the value isNull, then convert it to 0. like I normally do this isNull(value, 0). 如果值为isNull,则将其转换为0。就像我通常这样做的是isNull(value,0)。

SELECT * FROM 
( 
SELECT oa.OpptID, o.OpptName, ISNULL(Amount, 0) AS Amount, BucketNameID
FROM dbo.Opportunity o 
LEFT JOIN dbo.ProductBucketAmount oa ON oa.OpptID = o.OpptID
WHERE oa.OpptID IN (123, 456) 
) p
PIVOT
(
    Sum(p.Amount)
    FOR p.BucketNameID
    IN (
        [1], [2], [3], [4], [5]
    )   
) AS pvt

If I do like this for the PIVOT columns, it will works, but looks so messy codes. 如果我喜欢PIVOT列,它可以工作,但是看起来很乱。 Plus, I want to SELECT all columns everytime (SELECT * FROM...) 另外,我想每次都选择所有列(SELECT * FROM ...)

SELECT OpptName, OpptName, ISNULL([1], 0) AS '1', ISNULL([2], 0) AS '2'  ... etc ...

Please help or suggestion 请帮忙或建议

Thanks, 谢谢,

Yes, you have to do it outside of the pivot, so yes, it's somewhat messy. 是的,您必须在数据透视表之外执行此操作,因此,这有点混乱。 The reason is that some of those NULL s are being constructed by the pivot from no input rows - so there's no earlier stage at which you can convert the NULL s to 0 s. 原因是其中一些NULL数据透视表从无输入行构造 ,因此没有更早的阶段可以将NULL转换为0

And, as you've also discovered, the PIVOT clause itself isn't flexible. 而且,正如您还发现的那样, PIVOT子句本身并不灵活。 It has to have exactly an aggregate function specified, not an arbitrary expression containing the aggregate. 它必须确切地指定一个聚合函数,而不是包含该聚合的任意表达式。

So what you have: 所以你有:

SELECT OpptName, OpptName, ISNULL([1], 0) AS '1', ISNULL([2], 0) AS '2'  ... etc

is about the best that you can do. 是关于您能做的最好的事。 (And there's no way to do this as some form of SELECT * ... - you have to convert each column separately) (并且无法通过某种形式的SELECT * ...来执行此操作-您必须分别转换每列)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM