2014-05-06 63 views
0

下面是我創建的查詢,但在生成結果驗證後,查詢產生的結果不準確。在選擇子查詢中使用「分組依據」

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的多個記錄。但是,當我執行查詢時,我隨機選擇了一個最大(bill_dt)爲12/31/2013的acct_id進行驗證。我用acct_id查找了invoice_detail表,結果返回了一條bill_dt大於1/1/2014的附加記錄。我想確定2014年1月1日後沒有任何發票的acct_id。

+0

你不需要兩次加入invoice_detail(即子查詢)。只需將子查詢條件添加到主查詢。我不知道這是否會導致你的問題,但有一個更簡單的查詢應該幫助弄清楚。 –

回答

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