I am having an sql view "data", which looks like the following:
CALMONTH COSTCENTER Kontonummer FIELDNM003
202212 Alpha 123 10
202301 Alpha 123 20
202210 Alpha 223 50
202307 Beta 123 10
I want to keep only the combinations of "COSTCENTER" and "Kontonummer" which at least have an entry for "CALMONTH" >= 202301 .
The desired output would be:
CALMONTH COSTCENTER Kontonummer FIELDNM003
202212 Alpha 123 10
202301 Alpha 123 20
202307 Beta 123 10
Right now I am only able, to do it only for one column "COSTCENTER":
SELECT "t"."CALMONTH","t"."COSTCENTER","t"."Kontonummer","t"."FIELDNM003"
FROM "data" t
inner join (
select "COSTCENTER"
from "data"
group by "COSTCENTER"
having max("CALMONTH") > 202301
) as s on s.COSTCENTER = t.COSTCENTER
3
Answers
You should identify any COSTCENTER and Kontonummer pairs that have at least one entry where "CALMONTH" >= 202301. After finding these pairs, join them with your table to retrieve all corresponding rows :
Demo here
If you are using mysql 8 or higher, This is an other way to do it using window function
MAX()
:A simple exists query should do it:
You can use a simple
IN
clause because they work with multiple columns in MySQL:The inner query fetches all pairs that satisfy your date condition, the outer one adds the other columns.
Sample here: db<>fiddle