encina_china 2008-07-10 14:29
浏览 103
已采纳

有关case when语句在hibernate中使用时的问题??

各位达人,先听小弟的问题描述:

项目中需要完成一个报表功能,所以我先在mssql中使用了查询分析器,完成大致的sql语句,其功能已经达到了要求,代码如下
[code="java"]
select orgname, index_year, index_month,
sum(case when type='d'then 1 else 0 end), //当类型为‘d’是加1
sum(case when type='s' then 1 else 0 end), //当类型为‘s’是加1
sum(case when type='e' then 1 else 0 end), //当类型为‘e’是加1
sum(case when type='z' then 1 else 0 end), //当类型为‘z’是加1
sum(case when type!='s' then pprice else 0 end) from
(select sr.recid, datepart(year, sr.saledate) index_year,
datepart(month, sr.saledate) index_month,
u.cname, u.type, e.empname, o.orgname, p.pname, p.pprice
from t_sellrecord as sr, t_cuser as u, t_employment as e, t_organized as o, t_product as p
where datediff(month, sr.saledate ,getdate()) < 36

and o.recid = sr.saleorgid and sr.salesid = e.recid
and u.recid = sr.buyerid and p.recid = sr.proid )
x group by orgname, index_year, index_month order by orgname asc, index_year asc, index_month asc[/code]
然后直接考到java web项目中的dao中,使用hql语句,发现不支持datepart,所以改为直接sql,就使用了createSQLQuery,来进行查询,以上代码均未更改的直接copy了,查询结果另小弟十分疑惑。。。
sql查询分析器中是
eeee 2008 7 0 0 2 0 1000.0
aaaa 2008 7 0 2 0 0 0.0

bbbb 2008 7 0 0 2 0 1000.0
cccc 2008 7 0 1 0 0 0.0

dddd 2008 6 0 2 10 0 5000.0
dddd 2008 7 0 5 4 0 2000.0

而实际结果为
eeee 2008 7 0 0 0 0 0.0

aaaa 2008 7 0 0 0 0 0.0

bbbb 2008 7 0 0 0 0 0.0

cccc 2008 7 0 0 0 0 0.0

dddd 2008 6 0 0 0 0 0.0
dddd 2008 7 0 0 0 0 0.0
似乎,第一个sum中case when获取的结果把后面的值都覆盖了,
于是我试着吧type='d'改成1=1
sql查询分析器中是
eeee 2008 7 2 0 2 0 1000.0
aaaa 2008 7 2 2 0 0 0.0

bbbb 2008 7 2 0 2 0 1000.0
cccc 2008 7 1 1 0 0 0.0

dddd 2008 6 12 2 10 0 5000.0
dddd 2008 7 9 5 4 0 2000.0

而实际结果为
eeee 2008 7 2 2 2 2 2.0

aaaa 2008 7 2 2 2 2 2.0

bbbb 2008 7 2 2 2 2 2.0

cccc 2008 7 1 1 1 1 1.0

dddd 2008 6 12 12 12 12 12.0
dddd 2008 7 9 9 9 9 9.0

各位达人哇,我疑惑不解,疑惑不解,但求赐教~~跪谢 :cry: :cry:

  • 写回答

1条回答 默认 最新

  • newten710 2008-07-10 15:08
    关注

    sum函数后面追加下别名,as XX,就可以了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误