I have 2 tables one contains users and their data, the other contains payment transactions which are done but not limited to once per month. I'd like to query users who have not paid at least once. My table users table looks like so.
idu fname lname
1 John Doe
2 Jane Doe
3 Mary Jane
4 John Rancho
My payments table looks like so
payment_id uid payment_date
1 2 2012-01-07 08:00:00
2 3 2013-01-12 08:00:00
3 1 2012-02-01 08:00:00
4 2 2012-02-07 08:00:00
5 3 2013-02-12 08:00:00
6 1 2012-03-01 08:00:00
7 2 2015-04-08 08:00:00
8 1 2014-05-31 08:00:00
9 1 2014-07-31 08:00:00
I would love my results to look like the table shown below where unpaid times is the count of months not paid for and is greater than one.
IDU Name Unpaid Times
2 Jane Doe 3
3 Mary Jane 4
I did the query in PHP and MySQL in a crappy way though I get desired results. I want to transfer the code to Android and SQLite so an otimised query is highly required. My PHP/MySQL code is shown below. Thanks.
$query = "SELECT idu,fname,lname,date_added,payment_date FROM water_users LEFT JOIN payments ON idu=sold_to GROUP BY (CASE WHEN MONTH(payment_date) IS NULL THEN idu ELSE MONTH(payment_date) END) ORDER BY DATE(payment_date) ASC";
$result = $db->RunQueryForResults($query);
$defaulters = array();
while ($row = $result->fetch_assoc()) {
$start_date = $row['date_added'];
while (strtotime($start_date) < strtotime(getCurrentDate())) {
$current_month = date("Y-m", strtotime($start_date));
$payment_date = date("Y-m", strtotime($row['payment_date']));
if ((strtotime($current_month) !== strtotime($payment_date)) && (strtotime($payment_date) <= strtotime($current_month))) {
$defaulters[] = array(
'idu' => $row['idu'],
'name' => $row['fname'] . " " . $row['lname'],
'defaulted_month' => date("M Y", strtotime($current_month))
);
}
$start_date = date("Y-m-d H:i:s", strtotime("+30 day", strtotime($start_date)));
}
}
Aucun commentaire:
Enregistrer un commentaire