我有如下表格,
Txn_Id Txn_Type
___________________
1 101
1 102
1 103
1 104
2 101
2 102
2 104
3 101
3 104
我想要只有txn_type 101和104的行。例如,对于上面的数据我只能得到Txn_Id“3”。
我尝试了下面的结果。是否可以通过单一查询来实现此目的。
Select txn_id from Txn where txn_id in (Select txn_id from Txn where txn_id = 101) and txn_id =104.
答案 0 :(得分:3)
Select txn_id from Txn where txn_type in (101,104)
选项2
Select txn_id from Txn where (txn_type = 101 OR txn_type=104)
仅获得" 3"
Select distinct txn_id from Txn t1 where (txn_type = 101 OR txn_type=104)
and not exists(
select 1 from Txn t2 where t2.txn_type IN (102,103) and t2.txn_id = t1.txn_id
)
答案 1 :(得分:0)
您好根据您的上述评论,您只需要txn_id = 3(最大)
请找到以下代码。
DECLARE @Table1 TABLE
(txn_id int, Txn_Type int)
;
INSERT INTO @Table1
(txn_id , Txn_Type )
VALUES
(1, 101),
(1, 102),
(1, 103),
(1, 104),
(2, 101),
(2, 102),
(2, 104),
(3, 101),
(3, 104)
;
Select max(txn_id ),Txn_Type
from @Table1 where item in (101,104)
group by Txn_Type
答案 2 :(得分:0)
正如balaji指出的那样,@ Ayush解决方案并不灵活,因为如果您在表(4,101)和(4,104)中添加另一对记录,则会返回不正确的结果。 IMO,你必须将表连接到自己进行一些过滤,如下所示:
DECLARE @Table1 TABLE
(txn_id int, Txn_Type int);
INSERT INTO @Table1
(txn_id , Txn_Type )
VALUES
(1, 101),
(1, 102),
(1, 103),
(1, 104),
(2, 101),
(2, 102),
(2, 104),
(3, 101),
(3, 104),
(4, 101),
(4, 104);
select t1.*
from @Table1 t1
inner join (select txn_id, count(*) as total
from @Table1
group by Txn_id
having count(*) < 3
) t2 on t2.txn_id = t1.txn_id
where t1.Txn_Type in (101,104)