Search code examples
sqldateteradatateradata-sql-assistantteradatasql

SQL: 4 transfers in different months within the last 6 months and specific words in title in Teradata SQL?


I have table in Teradata SQL like below:

enter image description here

And I need to select only these rows, where:

  1. In title has (in any configuration, not case sensitive) words: "cash" or "pay"
  2. Have had at least 4 transfers in different months within the last 6 months (between 2021-01-03 and 2021-07-03)

So, I need as a result only ID = 111 because this ID has within last 6 months at least 4 title included "cash" or "pay" (in different months)

ID
----
111

(to put it simply, you have received a salary transfer at least 4 times in the last 6 months -- in diferent month)

I am aware that my sample table is not ideal for this case, because it prestns to small amount of rows, but I believe that description is clear!

I need to do it on Teradata SQL, what can I do that ?

To be more precision:

  1. Transfer -> is when title has "cash" or "pay" in any configuration, not case sensitive,
  2. ID is not unique in table, because some ID can received transfer for example 5 times,
  3. Table is constructed that you have payment list of your workers, and you want to find them which received at least 4 transfers in last 6 months (but each transfer in different month)

Solution

  • select id
    from tab
          -- title has (in any configuration, not case sensitive) words: "cash" or "pay"
    where title like any ('%cash%', '%pay%')
          -- last 6 months
      and date between add_months(current_date, -6) and current_date
    group by id
           -- at least 4 transfers in different months
    having count(distinct trunc(date, 'mon')) >= 4
    

    Unless title is defined CASESPECIFIC or you run an ANSI-mode session string comparisons are case-insensitive by default.