如何在日期范围内列出不同行中的mysql结果?

时间:2013-01-16 00:26:33

标签: mysql

我正在努力在页面上正确显示数据。我正在运行一个查询计费报告,该报告搜索所有未结账单,我想在一个页面上显示它们,余额显示余额的年龄。因此,如果客户ABC在过去一年中有10张发票,其中一些有未结余额,我希望在0-30 / 30-60 / 60-90 /和90天以上的列中显示这些余额。这就是我的......

    $sql17 = "SELECT $mysql_billing.primary_key, $mysql_billing.a_name, $mysql_billing.invoicedate, $mysql_billing.finaltotal, $mysql_billing_dates.paidtotal,
 ($mysql_billing.finaltotal - $mysql_billing_dates.paidtotal) AS total
 FROM
   (SELECT $mysql_billing.primary_key, $mysql_billing.a_name, $mysql_billing.login_username, $mysql_billing.invoicedate,
   SUM($mysql_billing.custotal) AS finaltotal 
   FROM $mysql_billing where $today >= invoicedate AND $start_search_prev180_date <= invoicedate AND custotal != payments GROUP BY login_username) $mysql_billing 
 LEFT JOIN 
   (SELECT $mysql_billing_dates.id, $mysql_billing_dates.username, 
   SUM($mysql_billing_dates.amount) AS paidtotal 
   FROM $mysql_billing_dates where complete != 'yes' GROUP BY username) $mysql_billing_dates 
 ON ($mysql_billing.login_username = $mysql_billing_dates.username) 
 GROUP BY a_name ORDER BY a_name ASC";

这似乎打印出结果,但是如何根据超过1个日期变量将结果导入不同的列?我是否必须进行4次单独查询?

2 个答案:

答案 0 :(得分:1)

你的SQL小提琴很接近,但你的一些连接不正确。

SELECT 
  billing.a_name, 
  billing.finaltotal, 
  billing_dates.paidtotal,
  (billing.finaltotal - billing_dates.paidtotal) AS total,
   billing.TimePeriod
FROM
   (SELECT 
      a_name, 
      login_username, 
      SUM(custotal) AS finaltotal,
      CASE 
        WHEN invoicedate > DATE_SUB(CURDATE(),INTERVAL 30 DAY) THEN '30'
        WHEN invoicedate > DATE_SUB(CURDATE(),INTERVAL 60 DAY) THEN '60'
        WHEN invoicedate > DATE_SUB(CURDATE(),INTERVAL 90 DAY) THEN '90'
        ELSE '90+'
      END AS TimePeriod

    FROM billing 
    where CURDATE() >= invoicedate 
      AND CAST(20120601 AS DATETIME) <= invoicedate 
    GROUP BY login_username) billing 
 LEFT JOIN 
   (SELECT 
      username, 
      SUM(amount) AS paidtotal 
    FROM billing_dates
    GROUP BY username) billing_dates 
   ON (billing.a_name = billing_dates.username) 
ORDER BY a_name ASC;

以下是更新后的Fiddle

答案 1 :(得分:0)

我建议为客户选择所有未完成的发票,然后使用代码将这些发票组织成每个时间段的列表。

使用单个查询可能会更快,并且可以轻松地对程序中的结果进行分类。

然后,您只需为每个列表选择一个元素以生成报告中的行。