我是sql的新手并拥有以下查询。有多行,因为在每个月的最后一天添加了一个新行。我想要做的是选择具有最新accounting_dt的记录。我一直试图在accounting_dt字段上使用max,但一直都会出错。任何帮助将不胜感激。如果有更好的方法来编写此查询,我也很感谢这些评论。正如我之前所说,我是新手,我希望学习正确的方法来做这些事情。再次感谢你的帮助。
SELECT
pa.BUSINESS_UNIT,
pdr.DEPTID,
pa.IN_SERVICE_DT,
pa.ASSET_ID,
pa.DESCR,
pb.LIFE,
pb.METHOD,
pdr.COST,
pdr.DEPR,
pdr.depr_ytd,
pdl.accounting_dt
from PS_ASSET pa,
PS_BOOK pb,
PS_DEPR_RPT pdr,
PS_DIST_LN pdl
where pa.BUSINESS_UNIT = 'A0056'
and pa.ASSET_ID = '000000000003'
and pb.BOOK = 'PERFORM'
and pdr.book = 'PERFORM'
and pdl.book = 'PERFORM'
and pdr.FISCAL_YEAR = '2014'
and pdr.ACCOUNTING_PERIOD = '12'
and pb.ASSET_ID= pa.ASSET_ID and pb.BUSINESS_UNIT = pa.BUSINESS_UNIT
and pdr.ASSET_ID= pa.ASSET_ID and pdr.BUSINESS_UNIT = pa.BUSINESS_UNIT
and pdl.ASSET_ID= pa.ASSET_ID and pdl.BUSINESS_UNIT = pa.BUSINESS_UNIT
and pdl.distribution_type = 'DE'
结果:
BU DEPTID INSERVDT IDNO DSCR LIFE METH COST DEPREC
ACCUMDP ACCT_DT
A0056 01-JAN-14 000000000003 Test 72 SL 500 7.36 659.75 31-JAN-14
A0056 01-JAN-14 000000000003 Test 72 SL 500 7.36 659.75 28-FEB-14
A0056 01-JAN-14 000000000003 Test 72 SL 500 7.36 659.75 31-MAR-14
A0056 01-JAN-14 000000000003 Test 72 SL 500 7.36 659.75 30-APR-14
A0056 01-JAN-14 000000000003 Test 72 SL 500 7.36 659.75 31-JUL-14
A0056 01-JAN-14 000000000003 Test 72 SL 500 7.36 659.75 31-JUL-14
A0056 01-JAN-14 000000000003 Test 72 SL 500 7.36 659.75 30-JUN-14
A0056 01-JAN-14 000000000003 Test 72 SL 500 7.36 659.75 30-JUN-14
答案 0 :(得分:0)
您应该了解明确的join
语法。它不仅使查询更具可读性,而且是更强大的符号。
我猜你想要每个BU
的最新记录。您可以使用row_number()
解决问题。以下是如何执行此操作的示例:
with t as (
<your query goes here>
)
select t.*
from (select t.*,
row_number() over (partition by bu order by accounting_dt desc) as seqnum
from t
) t
where seqnum = 1;