if(plimit)
query = strdup(
"SELECT c.id, ca.balance " "FROM customers c "
// balance
"JOIN (SELECT SUM(value) AS balance, customerid "
"FROM cash "
"GROUP BY customerid "
"HAVING SUM(value) < 0 "
") ca ON (c.id = ca.customerid) " // monthly assignments sum
"JOIN (SELECT "
"SUM(t.value * (CASE t.period "
"WHEN " _YEARLY_ " THEN 1/12.0 "
"WHEN " _HALFYEARLY_ " THEN 1/6.0 "
"WHEN " _QUARTERLY_ " THEN 1/3.0 "
"ELSE 1 END)) AS tariff, a.customerid "
"FROM assignments a "
"JOIN tariffs t ON (a.tariffid = t.id) " "WHERE a.period = 3 "
"AND a.suspended = 0 "
"AND (a.datefrom <= %NOW% OR a.datefrom = 0) "
"AND (a.dateto >= %NOW% OR a.dateto = 0) "
"GROUP BY a.customerid "
") t ON (t.customerid = c.id) "
"JOIN (SELECT SUM(l.value) AS liab, a.customerid "
"FROM assignments a JOIN liabilities l ON (a.liabilityid = l.id) "
"WHERE a.suspended = 0 AND (a.datefrom <= UNIX_TIMESTAMP() OR a.datefrom = 0) "
"AND (a.dateto >= UNIX_TIMESTAMP() OR a.dateto = 0) "
"GROUP BY a.customerid ) l ON (l.customerid = c.id)" "WHERE c.deleted = 0 "
"AND c.cutoffstop < %NOW% "
#ifdef USE_PGSQL
"AND balance * -1 > (?/100::numeric * (tariff+liab)) "
#else
"AND balance * -1 > (?/100 * (tariff+liab)) "
#endif
"%groups%egroups%nets%enets"
);
"