2017-12-19 4 views
1

Ich habe eine transactions Tabelle.MySQL Abfrage für Datumsbereich Transaktionen Anweisung

id account_id trx_date trx_type amount remarks 
------ ---------- ---------- -------- ------ --------- 
    1   1 2017-12-10 DEPOSIT  500 test 
    2   1 2017-12-11 DEPOSIT  500 test  
    3   1 2017-12-12 DEPOSIT  6000 test  
    4   1 2017-12-13 WITHDRAW  300 test  
    5   1 2017-12-13 DEPOSIT  200 test 

Ich möchte in diesem Format führen, aber ich kann nicht herausfinden, wie die Abfrage für das Abrufen von Daten wie folgt sein wird. Hier sind alle Felder gleich transactions Tabelle. op_bal, cl_bal sind dynamisches Feld.

date   trx_type  op_bal  amount  cl_bal 
2017-12-12  DEPOSIT   1000  6000   7000 
2017-12-13  WITHDRAW  7000  300    6700 
2017-12-13  DEPOSIT   6700  200    6900 
+1

Was ist die Logik/Kriterien hinter dieser Ergebnismenge? –

+0

params: account_id, frm_dt, to_dt –

+3

Er fragt nach der gewünschten Logik in der Ergebnismenge. Sieht aus wie 60000 sollte 6000 sein. – jit

Antwort

0

hallo für die gegebene Ausgabe ich this sqlfiddle erstellt haben für die Antwort bitte überprüfen

CREATE TABLE transactions (
    id bigint(12) PRIMARY KEY auto_increment, 
    account_id bigint(12), 
    trx_date date, 
    trx_type enum('DEPOSIT','WITHDRAW'), 
    amount float(10,2), 
    remarks varchar(50) 
); 

INSERT INTO transactions (account_id, trx_date, trx_type, amount, remarks) 
VALUES ('1','2017-12-10','DEPOSIT',500,'test'), 
     ('1','2017-12-11','DEPOSIT',500,'test'), 
     ('1','2017-12-12','DEPOSIT',6000,'test'), 
     ('1','2017-12-13','WITHDRAW',300,'test'), 
     ('1','2017-12-13','DEPOSIT',200,'test'); 

und Abfrage Ergebnis zu erzielen ist

SELECT 
trx_date, 
trx_type, 

(SELECT SUM(CASE tr.trx_type WHEN 'DEPOSIT' THEN CONCAT('+',tr.amount) ELSE CONCAT('-', tr.amount) END) as amount FROM transactions as tr WHERE tr.id < (SELECT MAX(t.id) FROM transactions as t WHERE t.id <= transactions.id LIMIT 1)) as op_bal, 
amount AS trx_amount, 
(SELECT SUM(CASE tr.trx_type WHEN 'DEPOSIT' THEN CONCAT('+',tr.amount) ELSE CONCAT('-', tr.amount) END) as amount FROM transactions as tr WHERE tr.id <= (SELECT MAX(t.id) FROM transactions as t WHERE t.id <= transactions.id LIMIT 1)) as cl_bal 
FROM transactions 
WHERE DATE(trx_date) BETWEEN '2017-12-12' AND '2017-12-13' 

Hoffe, es wird für Sie arbeiten.

+0

Es funktioniert nur für ID-basierte Datensätze. Das Ergebnis wird falsch und unerwartet angezeigt, wenn trx_date geändert wurde. Bitte überprüfen Sie diese [sqlfiddle] (http://sqlfiddle.com/#!9/8c3dd3/1) –

+0

Sie haben das Datum nach hinten aktualisiert, so dass Sie das Datum 2017-12-10 zu 2017-12-13 übergeben müssen –