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

时间:2014-05-06 19:09:24

标签: sql group-by

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

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_ids。

1 个答案:

答案 0 :(得分:0)

  

我想识别2014年1月1日之后没有任何发票的acct_ids

然后你的子查询中的条件必须是:

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