SUM结果值即使使用case语句也会重复

时间:2012-11-16 02:28:15

标签: java sql hibernate postgresql sum

我使用posgresql作为数据库,java作为hibernate的编程语言。我的问题是这个查询:

select cast(sum(CASE WHEN p.nropack > 0 THEN p.nropack ELSE 0 END) as integer),
cast(sum(CASE WHEN p.nropack < 0 THEN p.nropack ELSE 0 END) as integer),
cast(p.fechareg as date) 
from pronostico p 
inner join aeropuerto a on (a.idaeropuerto=p.idaeropuerto)
inner join ciudad c on (a.idciudad=c.idciudad)
inner join pais ps on (ps.idpais=c.idpais)
inner join continente ct on (ct.idcontinente=ps.idcontinente)
where c.idciudad=105
group by cast (p.fechareg as date);

结果我得到了:

sum;sum;fechareg 
30;-15;"2012-11-15"

但是当我在我的程序中使用它时:

public ArrayList<RepKardex> listarKardex(int ciud){  
    ciud=105; 
    ArrayList<RepKardex> listaKardex = new ArrayList<>();
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();        
    String q = "select cast(sum( case when p.nropack > 0 then p.nropack ELSE 0 end ) as integer), "
            + "cast(sum( case when p.nropack < 0 then p.nropack ELSE 0 end ) as integer), "
            + "cast(p.fechareg as date) "
            + "from Pronostico p "
            + "inner join Aeropuerto a on (p.idaeropuerto = a.idaeropuerto) "
            + "inner join Ciudad c on (a.idciudad = c.idciudad) "
            + "inner join Pais ps on (c.idpais = ps.idpais) "
            + "inner join Continente ct on (ct.idcontinente = ps.idcontinente) "
            + "where c.idciudad = :ciud "
            + "group by cast(p.fechareg as date) ";                    
    Query query = session.createSQLQuery(q);        
    query.setInteger("ciud", ciud);
    List lista = query.list();        
    Iterator iter = lista.iterator(); 
    while (iter.hasNext()) {    
        Object[] row = (Object[]) iter.next();            
        if (row!=null){
            System.out.println("entrantes : "+(Integer)row[0]); 
            System.out.println("salientes : "+(Integer)row[1]); 
            RepKardex rep = new RepKardex((int)row[0],(int)row[1],(Date)row[2]);              
            listaKardex.add(rep);
        }

    }

    tx.commit();
    session.close();

    return listaKardex;
} 

打印

entrantes: 30
salida:    30

即使我在查询中使用case语句,有人可以帮我弄清楚为什么它会重复正数吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用LEAST and GREATEST简化查询:

SELECT sum(GREATEST(p.nropack, 0))::int AS entrantes
      ,sum(LEAST(p.nropack, 0))::int AS salida
      ,p.fechareg::date AS fechareg
from   pronostico  p 
JOIN   aeropuerto  a ON a.idaeropuerto = p.idaeropuerto
JOIN   ciudad      c ON c.idciudad = a.idciudad
JOIN   pais       ps ON ps.idpais = c.idpais
JOIN   continente ct ON ct.idcontinente = ps.idcontinente
where  c.idciudad = 105
GROUP  BY p.fechareg::date;

除此之外它看起来很好。我认为第二列无法返回正数。这里还有其他一些问题。

编辑:

Comment by @hvd帮助发现客户端代码似乎被相同的列名混淆(两个和列都默认为"sum")。显式列别名似乎解决了这个问题。