简体   繁体   English

SQL语句使用大小写,例如,并具有

[英]SQL statement using case, like, and having

I am using an Oracle based system. 我正在使用基于Oracle的系统。

How do you use like, having, and a case statement together? 您如何一起使用like,having和case语句?

I am basically trying to list all of the unique individuals that are found in a transactional table that have more than 4 "Class A" transactions, or more than 1 "Class B" transactions. 我基本上是试图列出在事务表中找到的所有唯一个体,这些个体具有超过4个“ A类”交易或超过1个“ B类”交易。 The reason why I want to use like is because the only way to diferentiate between transaction classes is by using a like statement in the transaction type column. 之所以要使用like是因为在事务类之间进行区分的唯一方法是在transaction type列中使用like语句。

For example, there are many transaction types, but only "Class A" have '%ABC%' as part of their transaction type, and "Class B" are all the other types that do not have '%ABC%' in their transaction type column. 例如,交易类型很多,但是只有“ A类”的交易类型中包含'%ABC%' ,而“ B类”是所有其他类型的交易中不包含'%ABC%'的交易输入列。

So again, I want my query to return only the indiv ids that have more than 4 "Class A" Transactions, or 1 "Class B" transaction. 再次重申,我希望查询仅返回具有4个以上“ Class A”事务或1个“ Class B”事务的个人ID。

here is what I have so far: 这是我到目前为止所拥有的:

select tt.indiv_id, count(*) from transactiontable tt
group by tt.indiv_id
case when tt.tran_type like '%ABC'
having count(*) > 4
else
having count(*)>1.

I have searched a good bit on the site and I have not found an example using all of these functions together. 我在网站上搜索了很多内容,但没有找到将所有这些功能结合使用的示例。

select tt.indiv_id, 
    count(case when tt.tran_type like '%ABC' then 1 end) as ClassACount,
    count(case when tt.tran_type not like '%ABC' then 1 end) as ClassBCount
from transactiontable tt
group by tt.indiv_id
having count(case when tt.tran_type like '%ABC' then 1 end) > 4
    or count(case when tt.tran_type not like '%ABC' then 1 end) > 1

Try this 尝试这个

select tt.indiv_id, count(*) 
from transactiontable tt  
group by tt.indiv_id, tt.tran_type
having count(*) > case when tt.tran_type like '%ABC' then 4 else 1 end

Your query is close. 您的查询已关闭。 You want to keep track of each transaction type separately in the having clause: 您希望在having子句中分别跟踪每种交易类型:

select tt.indiv_id, count(*)
from transactiontable tt
group by tt.indiv_id
having sum(case when tt.tran_type like '%ABC%' then 1 else 0 end) > 4 or
       sum(case when tt.tran_type not like '%ABC%' then 1 else 0 end) > 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM