[英]How to filter records based on minimum date and some other criteria where each transaction can have multiple dates in SQL?
I want to extract transaction where quantity is -1 on very first date of the same transaction. 我想在同一笔交易的第一天提取数量为-1的交易。 Assume that single transaction have multiple rows. 假设单个事务有多行。
We have following table 我们有下表
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
----------------------------------
All I want to extract only those transactions which do not have quantity -1 on its first entry within same transaction ID. 我只想提取那些在同一交易ID中的第一个条目中没有数量为-1的交易。
Expected results should be like this 预期结果应该是这样的
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
----------------------------------
try like below using subquery 尝试像下面使用子查询
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
)
this one should work 这个应该工作
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
)
I think the simplest method is aggregation: 我认为最简单的方法是聚合:
select txid_id
from t
group by txid_id
having min(date) = min(case when qty = -1 then date end);
The having
clause simply says that the minimum date is the minimum of the date where qty = -1
. having
子句只是说最小日期是qty = -1
的最小日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.