带有NULL值的MySQL问题

时间:2015-11-24 11:18:01

标签: mysql db2 bigdata biginsights bigsql

我有一个包含字段的表:country_code,short_name,currency_unit,a2010,a2011,a2012,a2013,a2014,a2015。 a2010-a2015字段是double的类型。

如何根据字段a2010-a2015的平均值进行查询,并记住这些字段可能具有NULL值?

我尝试了这段代码并且它不起作用(返回一个错误,它告诉ORDER BY部分有什么问题。错误是说了一些关于coumn名字和GROUP BY的内容)。逻辑是:ORDER BY((A)/(B))其中A - 非NULL字段的总和和B - 非NULL字段的数量。

有什么想法吗?

(如果重要的话,代码将在BigInsights环境中使用)

SELECT country_code, short_name, currency_unit, a2010, a2011, a2012, 
a2013, a2014, a2015
FROM my_schema.my_table
WHERE Indicator_Code = 'SE.PRM.TENR'
ORDER BY 
(
(
Coalesce(a2010,0) + Coalesce(a2011,0) + Coalesce(a2012,0)  
+Coalesce(a2013,0) + Coalesce(a2014,0) + Coalesce(a2015,0)
)
/
(
COUNT(Coalesce(a2010)) + COUNT(Coalesce(a2011)) + COUNT(Coalesce(a2012)) 
+ COUNT(Coalesce(a2013)) + COUNT(Coalesce(a2014)) + 
COUNT(Coalesce(a2015))
)
) DESC;

1 个答案:

答案 0 :(得分:0)

使用MySQL ifnull

IFNULL(expression_1,expression_2)
在您的查询中

: -

IFNULL(
(
COUNT(Coalesce(a2010)) + COUNT(Coalesce(a2011)) + COUNT(Coalesce(a2012)) 
+ COUNT(Coalesce(a2013)) + COUNT(Coalesce(a2014)) + 
COUNT(Coalesce(a2015))
),
1
)
相关问题