可以在h2字符串中使用ISNULL或IFNULL

时间:2018-04-02 16:56:46

标签: sql spring jdbc h2

我正在计算每月的平均数量,我正在使用h2这样的查询

SELECT t.truckCode,   
        monthname(orderDate)  as month, 
        IFNULL (avg(petrolQty),0) as avgPetrolQty 
from  
   truck t left join orderz o 
on 
   t.truckId = o.truckId 
group by t.truckCode, monthname(orderDate) 
order by t.truckCode, monthname(orderDate)

所以我得到0如果avg为null这是好的但它是我想要使用的左连接,所以我可以看到系统中的所有卡车。问题是当卡车从未有过订单monthname(orderDate)返回null时,我怎么能改变它来获得一些默认值,我试过ifnull但是没有用,我宁愿返回一个字符串,例如,未公布

对于查询,这是我的结果

TRUCKCODE   MONTH   AVGPETROLQTY  
BY2004  null    0.0
BY2354  January 13.0
BY2874  January 13.0
BY2994  null    0.0
BY8754  January 13.0

如何将null更改为某个默认字符串

 SELECT t.truckCode,  COALESCE(monthname(orderDate),'Not Announced')  as month,  IFNULL (avg(petrolQty),0) as avgPetrolQty 
from  truck t left join orderz o  
on  t.truckId = o.truckId 
group by t.truckCode, monthname(orderDate)  
order by t.truckCode, orderDate

1 个答案:

答案 0 :(得分:1)

您可以使用COALESCE功能检查月份是否为空,然后使用默认值,例如“未公布”。

SELECT t.truckCode,   
        COALESCE(monthname(orderDate),'Not Announced')  as month, 
        IFNULL (avg(petrolQty),0) as avgPetrolQty 
from  
   truck t left join orderz o 
on 
   t.truckId = o.truckId 
group by t.truckCode, COALESCE(monthname(orderDate),'Not Announced') 
order by 1,2;

Result:
TRUCKCODE   MONTH   AVGPETROLQTY  
BY2004  Not Announced 0.0
BY2354  January 13.0
BY2874  January 13.0
BY2994  Not Announced    0.0
BY8754  January 13.0