簡體   English   中英

如何根據最小日期和其他條件(其中每個事務在SQL中可以具有多個日期)過濾記錄?

[英]How to filter records based on minimum date and some other criteria where each transaction can have multiple dates in SQL?

我想在同一筆交易的第一天提取數量為-1的交易。 假設單個事務有多行。

我們有下表

tXid_ID     Date        Qty
---------------------------------------
1       1/2/2014    -1
2       2/3/2014    1
2       3/3/2014    1
3       4/3/2014    1
4       5/3/2014    -1
4       6/3/2014    1
5       7/3/2014    -1
5       8/3/2014    1
6       9/3/2014    1
7       10/3/2014   1
7       11/3/2014   -1
----------------------------------

我只想提取那些在同一交易ID中的第一個條目中沒有數量為-1的交易。

預期結果應該是這樣的

tXid_ID     Date        Qty
---------------------------------------
2       2/3/2014    1
2       3/3/2014    1
3       4/3/2014    1
6       9/3/2014    1
7       10/3/2014   1
7       11/3/2014   -1
----------------------------------

嘗試像下面使用子查詢

 select a.* from table_name a
 where tax_id not in (  select tax_id from table_name t1
    where t1.date= (select min(date) from 
                table_name t2 where t1.tax_id=t2.tax_id
               ) and  t1.qty=-1
)

這個應該工作

select
  *
from
  tbl
where
  tXid_ID in (
    select
      t.tXid_ID
    from
      tbl t
      inner join (
        select
          min(date) as minDate,
          tXid_ID
        from
          tbl
        group by
          tXid_ID
      ) t1 on t1.minDate = t.date
    where
      t.Qty != -1
  )

我認為最簡單的方法是聚合:

select txid_id
from t
group by txid_id
having min(date) = min(case when qty = -1 then date end);

having子句只是說最小日期是qty = -1的最小日期。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM