sql >> Database >  >> RDS >> Mysql

PHP MYSQLi gebruiken om alleen debiteuren en alleen crediteuren te beheren met action_type DR en CR

Het lijkt erop dat je gewoon je HAVING . moet aanpassen clausule, om gevallen uit te filteren waarin balance is ofwel meer dan nul (Debiteur) OF balance is kleiner dan nul (crediteur).

U kunt ook voorwaardelijke IF() . gebruiken uitdrukkingen om dr/cr . te bepalen in het balance kolom.

Om Debiteuren te krijgen alleen:

SELECT client_id, 
       Sum(Coalesce(CASE 
                      WHEN action_type = 'dr' THEN amount 
                    end, 0)) AS total_debits, 
       Sum(Coalesce(CASE 
                      WHEN action_type = 'cr' THEN amount 
                    end, 0)) AS total_credits, 
       Sum(Coalesce(CASE 
                      WHEN action_type = 'cr' THEN amount 
                    end, 0)) - Sum(Coalesce(CASE 
                                              WHEN action_type = 'dr' THEN 
                                              amount 
                                            end, 0)) AS total_debtors, 
       IF(Sum(Coalesce(CASE 
                         WHEN action_type = 'cr' THEN amount 
                       end, 0)) - Sum(Coalesce(CASE 
                                                 WHEN action_type = 'dr' THEN 
                                                 amount 
                                               end, 0)) > 0, 'dr', 'cr') AS balance 
FROM   tbl_balancesheet 
GROUP  BY client_id 
HAVING balance = 'dr' AND total_debtors <> 0

Creditors . krijgen alleen:

SELECT client_id, 
       Sum(Coalesce(CASE 
                      WHEN action_type = 'dr' THEN amount 
                    end, 0)) AS total_debits, 
       Sum(Coalesce(CASE 
                      WHEN action_type = 'cr' THEN amount 
                    end, 0)) AS total_credits, 
       Sum(Coalesce(CASE 
                      WHEN action_type = 'cr' THEN amount 
                    end, 0)) - Sum(Coalesce(CASE 
                                              WHEN action_type = 'dr' THEN 
                                              amount 
                                            end, 0)) AS total_debtors, 
       IF(Sum(Coalesce(CASE 
                         WHEN action_type = 'cr' THEN amount 
                       end, 0)) - Sum(Coalesce(CASE 
                                                 WHEN action_type = 'dr' THEN 
                                                 amount 
                                               end, 0)) > 0, 'dr', 'cr') AS balance 
FROM   tbl_balancesheet 
GROUP  BY client_id 
HAVING balance = 'cr' AND total_debtors <> 0


  1. Oracle-database blijft oneindig hangen in UPDATE-query's

  2. Hoe krijg ik ASCII-waarde in Oracle?

  3. Wijzigen op grote tafel in RDS Oplossing voor tabel vol Fout

  4. Maak PostgreSQL-database on-the-fly met Hibernate, zelfs als de DB niet bestaat