vendredi 22 mars 2019

MySQL - Conditional GROUP BY based on characters from Max()

The Problem

I am producing a report that calculates monthly invoice sub-item sold. There are 2 types of invoices name:

  1. Ending with just a number 2, 3, 4 as the n'th invoice for that project (18000018J2)
  2. Ending with a #2, #3, #4 as a revises invoice (18000018J#2)

Behavior: For the monthly report, every Type-1 invoice are suppose to show, whereas for the revision (Type-2) only the last revision (Max) is suppose to be accounted for.

The problem is that I cannot seem to create a conditional invoice list that supports the behavior mentioned.

There is a much bigger query around this part of code but the overall monthly report will include WHERE Invoice.Number IN (.. and that is the following list that I am having problem with:

SELECT @max:=MAX(Invoice.Number) as Number FROM Invoice WHERE InvMonth="01" AND InvYear="2018" GROUP BY (CASE WHEN @max LIKE '%#%' THEN Invoice.ProjectID ELSE Invoice.Number END)

GROUP BY Options:

  • Invoice.ProjectID is always the same so it gets the Max() with it's a revision (type-2)
  • Invoice.Number is always different so the Max() is itself for when you want to include all invoices (Type-1)

Expected Result

If those 2 invoices are for the month of January 2018:

  • 18000018J
  • 18000018J#2

The result should be 18000018J#2 as you only want the last revision

If those 2 invoices are for the month of January 2018:

  • 18000018J
  • 18000018J2

The result should be 18000018J, 18000018J2 as you want both for the monthly calculation.

I am not planning to do anything about both issues combined, that is having an invoice that is both Type-1 and Type-2 such as 18000018J3#2, but if the solution also includes it that would be phenomenal (but not expected).

Aucun commentaire:

Enregistrer un commentaire