如何使用按日期分组的SUM()和MAX()连接2个表

时间:2015-03-01 06:21:11

标签: php mysql

我有表loadhistory(计划到"每个日期只选择最高值"按日期分组和按日期DESC排序)

| user_id | customer_id |     date    | bal |
    1           1         2015-02-27    500
    2           1         2015-02-27    650
    3           1         2015-02-28    450
    4           1         2015-02-28    620

和表事务记录(并计划使用SUM(bal)组和按日期DESC排序每个日期的值)

| user_id | customer_id |     date     | bal |
    1           1         2015-02-27     50
    2           1         2015-02-27     20
    3           1         2015-02-28     10

但我想加入两个看起来像这样的表:

|    date    |   balance    |   amount paid   |
  2015-02-28       620               10
  2015-02-27       650               70

我不善于加入表格。到目前为止,这是我的代码,无法正常工作

$q = "SELECT a.customer_id, SUM(a.bal), a.date, MAX(b.bal) GROUP BY date 
FROM transactionrecord as a 
LEFT JOIN loadhistory as b ON b.customer_id = a.customer_id
WHERE customer_id = {$_COOKIE['id']} GROUP BY date 
ORDER BY date DESC";
$r = @mysqli_query ($dbc, $q );

echo '<table align="center" cellspacing="0" cellpadding="5" width="45%">
<tr>
<td align="center"><b>Date</b></td>
<td align="center"><b>Balance</b></td>
<td align="center"><b>>Amount Paid></b></td>
</tr>';
    while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
    echo '
    <td align="center">' . $row['date'] . '</td>
    <td align="center">' . $row['MAX(b.bal)'] . '</td>
    <td align="center">' . $row['SUM(a.bal)'] . '</td>

';  

在我的查询中要更改什么来加入包含SUM()和MAX()的2个表?我使用的是$ row [&#39; &#39;]在echo中对吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

您的SQL语句应该如下所示,以达到您想要的结果:

SELECT a.customer_id, a.date, MAX(COALESCE(b.bal, 0)) AS bal, a.paid
FROM (
  SELECT customer_id, date, SUM(bal) AS paid
  FROM transactionrecord
  GROUP BY customer_id, date
) AS a LEFT JOIN loadhistory AS b
  ON a.customer_id = b.customer_id AND a.date = b.date
WHERE a.customer_id = 1
GROUP BY a.customer_id, a.date, a.paid
ORDER BY a.date DESC

在您的php中,您无法使用MAX(b.bal)SUM(a.bal)来引用结果列;相反,您必须按照我上面所做的那样为列添加别名。因此,您可以将MAX(b.bal)称为bal,您可以将SUM(a.bal)称为paid

你们大多数都拥有SQL权利,我只是

  • 删除了错误的GROUP BY表达式,
  • 为汇总的SUMMAX)列添加了别名,
  • 将事务余额汇总放在子查询中,以防止loadhistory表中多行的乘法结果
  • datecustomer_id列的所有提及进行了限定,因为这些列都显示在两个表中,
  • COALESCE上添加了bal,以防左联接导致没有匹配的loadhistory记录,
  • date上添加了加入条件,因为记录必须具有与您的要求相当的customer_iddate,并且
  • customer_id添加到GROUP BY子句中,因为SELECT子句中的任何非聚合字段都应位于GROUP BY子句中,以获得可预测的结果。

如果您想在表格user_id而不是date中选择loadhistoryMAX(bal)个最高的值,则需要执行以下操作:

SELECT b.user_id, a.customer_id, a.date,
  COALESCE(b.bal, 0) AS bal, SUM(a.bal) AS paid
FROM transactionrecord AS a LEFT JOIN (
  SELECT h1.user_id, h1.customer_id, h1.date, h1.bal
  FROM loadhistory h1 INNER JOIN (
    SELECT MAX(user_id) AS user_id, customer_id, date
    FROM loadhistory GROUP BY customer_id, date
  ) AS h2 ON h1.user_id = h2.user_id
         AND h1.customer_id = h2.customer_id
         AND h1.date = h2.date
) AS b ON a.customer_id = b.customer_id AND a.date = b.date
WHERE a.customer_id = 1
GROUP BY b.user_id, a.customer_id, a.date, b.bal
ORDER BY a.date DESC