Task: Add a new document header (one insert command); -Number of document = last document number + 1; -Date = current date; -Type = expense, if the documents of the "receipt" type are greater than the documents of the "expense" type. Otherwise, the type = receipt. - Consider that in the DMZ table initially there may not be a single row.
Table DMZ - document. DDM - date, NDM-document number, PR - receipt / expense (1-receipt, 2-consumption) of the goods. The request itself is:
INSERT INTO DMZ (DDM, NDM, PR) SELECT GETDATE() DDM, (isnull((SELECT MAX(NDM) FROM DMZ), 0) + 1) NDM, CASE WHEN isnull((SELECT COUNT(*) FROM DMZ WHERE PR = 1), 0) > isnull((SELECT COUNT(*) FROM DMZ WHERE PR = 2), 0) THEN 2 ELSE 1 END The query works, but you need to optimize it by replacing two queries in the CASE operator with one. How to do this?
I insert the diagram, if something helps.
