[英]How to only select rows where one column is unique and the other is a certain value
I am trying to figure out which ids only have one type of transaction.我想弄清楚哪些 ID 只有一种类型的交易。
I have tried joining and selecting distinct but I am doing it wrong我试过加入并选择不同的但我做错了
select transactions.type, id
from datasource
group by id, transactions.type
This gives me a table with two transaction types: either dep or withdraw.这给了我一个包含两种事务类型的表:dep 或withdraw。 Most IDs have two rows, one being dep and the other withdraw.
大多数ID有两行,一是dep,另一行是withdraw。 I want to select only the ids that have only the withdraw transaction type
我只想选择只有提款交易类型的 ID
use where condition and not exists
使用 where 条件和
not exists
select transactions.type, id from datasource t1
where type='withdraw'
and not exists( select 1 from datasource t2 where t1.id=t2.id
and type='dep')
You can use group by
with having count(*)=1
clause您可以将
group by
与having count(*)=1
子句一起使用
select id
from datasource
where transactions_type in
(
select transactions_type, id
from datasource
group by transactions_type
having count(*)=1 )
Since "You are trying to figure out which ids only have one type of transaction"由于“您正在尝试找出哪些 ID 只有一种类型的交易”
If you specifically look for transactions_type = 'withdraw'
, then add and transactions_type = 'withdraw'
to the end of the above Select Statement.如果您专门查找
transactions_type = 'withdraw'
,则将and transactions_type = 'withdraw'
到上述 Select 语句的末尾。
PS I suppose there's a type for transactions.type
, and that should be transactions_type
, isn't that? PS 我想
transactions.type
有一个类型,应该是transactions_type
,不是吗?
I think aggregation does what you want.我认为聚合可以满足您的需求。 However, I am confused what your data structure is.
但是,我很困惑你的数据结构是什么。 A
join
is needed somewhere:某处需要
join
:
select ds.id, min(t.type)
from datasource ds join
transactions t
on ds.? = t.? -- what is the join key?
group by ds.id
having min(t.type) = max(t.type);
If transactions.type
is actually a column in datasource
, then:如果
transactions.type
实际上是datasource
一列,则:
select ds.id, min("transactions.type")
from datasource ds
group by ds.id
having min("transactions.type") = max("transactions.type");
Similar to other answers, but simpler:与其他答案类似,但更简单:
select id, count(distinct transactions.type)
from datasource
group by id
having count(distinct transactions.type) = 1
It is unclear, however, what transactions.type is.然而,不清楚transactions.type 是什么。 It doesn't appear to be valid as a column name.
它似乎作为列名无效。 Or did you mean to write
transactions_type
?或者你的意思是写
transactions_type
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.