![](/img/trans.png)
[英]select records with dates in where condition and group the results based on each date
[英]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.