繁体   English   中英

在选择子查询中使用“分组依据”

[英]Using “Group By” in a Select Sub-Query

下面是我创建的查询,但是在验证产生的结果后,该查询产生的结果不准确。

select a.acct_id, c.bill_dt
from account a inner join invoice_detail b  on a.acct_id = b.acct_id 
inner join 
    (select acct_id, max(bill_dt) as bill_dt from invoice_detail  
    where bill_dt < '1/1/2014'
    group by acct_id)c on b.acct_id = c.acct_id
and a.acct_stat_id = '275'
and not a.acct_id in (select acct_id from contract where cntrct_stat_id in ('394','554','555','556'))
and not a.acct_id in (select acct_id from billing_adj where bill_adj_stat_id in ('4','394','553','554','555'))
group by a.acct_id, c.bill_dt
order by a.acct_id ASC

我希望我的结果在满足所有查询条件后仅显示acct_ids和max(bill_dt)。 invoice_detail表包含acct_id的多个记录。 但是,当我执行查询时,我随机选择了一个max(bill_dt)为12/31/2013的acct_id进行验证。 我在acct_id的invoice_detail表中查找,结果返回了bill_dt大于2014年1月1日的其他记录。 我想确定2014年1月1日之后没有任何发票的acct_id。

我想确定2014年1月1日之后没有任何发票的acct_id

然后,您的子查询中的条件需要为:

HAVING max(bill_dt) < '1/1/2014'

除了在子查询中之外,您还没有使用invoice_detail表,因此可以将其从主查询中删除:

select a.acct_id, c.bill_dt
from account a 
inner join 
    ( select acct_id, max(bill_dt) as bill_dt from invoice_detail  
      group by acct_id
      HAVING max(bill_dt) < '1/1/2014'
    ) c on a.acct_id = c.acct_id
and a.acct_stat_id = '275'
and not a.acct_id in (select acct_id from contract where cntrct_stat_id in ('394','554','555','556'))
and not a.acct_id in (select acct_id from billing_adj where bill_adj_stat_id in ('4','394','553','554','555'))
group by a.acct_id, c.bill_dt
order by a.acct_id ASC

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM