SQL issue
#634
Replies: 1 comment 2 replies
-
I wrote a small online reproduction to make it easier to collaborate on your problem: https://www.db-fiddle.com/f/w8xD9t2qLgdRv7t51HAaAn/0 Here is a suggestion for a slightly more readable version of the query: WITH OverdueInstallments AS (
SELECT
i.contractId,
i.dueDate,
i.deadlineDate,
i.paidAt,
DATEDIFF(CURDATE(), DATE_ADD(i.deadlineDate, INTERVAL 10 DAY)) AS daysOverdue,
DATEDIFF(i.paidAt, DATE_ADD(i.deadlineDate, INTERVAL 10 DAY)) AS daysPaidAfter
FROM installment i
),
FirstUnpaidInstallment AS (
SELECT
contractId,
MIN(dueDate) AS firstDueDate
FROM OverdueInstallments
WHERE paidAt IS NULL AND daysOverdue > 0
GROUP BY contractId
),
StatusCodes AS (
SELECT
o.contractId,
o.dueDate,
CASE
-- For unpaid installments
WHEN o.paidAt IS NULL AND o.dueDate = f.firstDueDate THEN
CASE
WHEN o.daysOverdue <= 0 THEN '0'
WHEN o.daysOverdue >= 180 THEN 'W'
ELSE 1+FLOOR(o.daysOverdue / 30)
END
-- For paid installments
ELSE
CASE
WHEN o.daysPaidAfter <= 0 THEN '0'
WHEN o.daysPaidAfter >= 180 THEN 'W'
ELSE 1+FLOOR(o.daysPaidAfter / 30)
END
END AS status
FROM OverdueInstallments o
LEFT JOIN FirstUnpaidInstallment f ON o.contractId = f.contractId
)
SELECT
c.id AS contractId,
c.name AS contractName,
(
SELECT GROUP_CONCAT(s.status ORDER BY s.dueDate DESC SEPARATOR '')
FROM StatusCodes s
WHERE s.contractId = c.id
) AS "Payment History Status Code"
FROM contract c; Concerning the replacements, I'm not sure I understand your question. What replacements do you want to do under which conditions ? |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, I’m working on a SQL query that includes a nested select statement. I need to modify it so that the first non-zero value from the right in a "history code" is replaced with a sequence of consecutive numbers, based on certain conditions.
For example, if the history code is 0302230, I want to transform it into 0302232100. In this example, the 3 (which is the first non-zero value from the right) is replaced with 3210, resulting in 03022(3210)0.
The replacement logic depends on conditions involving two dates: paidAt and deadlineDate. Below is the SQL code I’m currently working with:
Beta Was this translation helpful? Give feedback.
All reactions