当我将数据从数据库导出到客户端时,我遇到了SQL问题
我的工作要求是:
select
datmvt as DATE_MVT,
(select TRUNC(datmvt,-4) from dual ) as exercice,
codpro as CODPRO,
SUM(qtemvt)-SUM(C01) as QT
from myTable
where codpro = 'XXX'
and datmvt BETWEEN YYYYMMDD and YYYYMMDD
GROUP BY datmvt, codpro
HAVING abs(SUM(qtemvt)-SUM(C01)) > 0
给我这个结果:
DATMVT exercice codpro QT
20190119 20190000 0828765332927 1
20190126 20190000 0828765332927 -1
20180117 20180000 0828765332927 -1
20180118 20180000 0828765332927 -1
20190122 20190000 0828765332927 1
在您询问之前,是的,日期以YYYYMMDD格式存储为整数值。
我的请求正在运行,但我想添加以下内容:
exercice codpro QT
20190000 0828765332927 -1
20180000 0828765332927 -2
因此,我试图按exercice
订购,但Oracle回答:00904. 00000 - "%s: invalid identifier"
这是我无法使用但需要的请求:
select
(select TRUNC(datmvt,-4) from dual ) as exercice,
codpro as CODPRO,
SUM(qtemvt)-SUM(C01) as QT
from myTable
where codpro = 'XXX'
and datmvt BETWEEN YYYYMMDD and YYYYMMDD
GROUP BY exercice, codpro
HAVING abs(SUM(qtemvt)-SUM(C01)) > 0
答案 0 :(得分:2)
您只能引用GROUP BY
中数据集中存在的列,因此也需要在该位置重复该计算,例如:
select
TRUNC(datmvt,-4) as exercice,
codpro as CODPRO,
SUM(qtemvt)-SUM(C01) as QT
from myTable
where codpro = 'XXX'
and datmvt BETWEEN YYYYMMDD and YYYYMMDD
GROUP BY TRUNC(datmvt,-4), codpro
HAVING abs(SUM(qtemvt)-SUM(C01)) > 0
答案 1 :(得分:2)
我不知道您为什么在没有日期的情况下使用子查询(select TRUNC(datmvt,-4) from dual)
作为日期。您可以从select中进行选择,但是此语法更简单,应该可以完成工作:
select trunc(datmvt,-4) exercice, codpro, sum(qtemvt)-sum(c01) qt
from mytable
where codpro = '0828765332927' and datmvt between 20150101 and 20191231
group by trunc(datmvt, -4), codpro
having sum(qtemvt) - sum(c01) <> 0