如何排序和添加我的数据库记录?

时间:2011-11-08 12:16:39

标签: php mysql

  

可能重复:
  How to sort by previous date in database?

我想做的是从mysql中选择以前的日期记录,然后从我的数据库记录中选择我需要添加按日期排序的金额

我的数据库记录:

amount | date
2.0    | 2011-10-01
1.4    | 2011-10-02
2.6    | 2011-10-01
2.3    | 2011-10-02
4.4    | 2011-10-01
5.6    | 2011-10-03
6.3    | 2011-10-01

我想在界面中显示的内容:

amount | date
2.0    | 2011-10-01
2.6    | 2011-10-01
4.4    | 2011-10-01
6.3    | 2011-10-01
---------------------------
15.3   | 2011-10-01


1.4    | 2011-10-02  
2.3    | 2011-10-02
----------------------------
3.7    | 2011-10-02


5.6    | 2011-10-03
----------------------------
5.6    | 2011-10-03

我的代码(不起作用):

$Current = date("Y-m-d" ,strtotime("now"));
$query=mysql_query("SELECT * from item where date < $Current order by date");     
    while($re=mysql_fetch_array($query)){
    echo $total = $total + $re['amount'];
    echo $re['date'];
    }

这不能很好地运作吗?

感谢

3 个答案:

答案 0 :(得分:2)

您是否查看了MySQL的WITH ROLLUP选项。

像这样的东西

SELECT date,amount,item_id FROM table GROUP BY date,item_id WITH ROLLUP

答案 1 :(得分:0)

1)您可以查询要显示的每个日期

SELECT *, SUM(amount) FROM table WHERE date = @date;

2)您可以查询所有日期,并查询总计

- 表格行:

SELECT * FROM table WHERE date < @date ORDER BY date;

- 表总数:

SELECT SUM(amount) FROM table WHERE date < @date GROUP BY date ;

你可以在一个查询中做第二个选项,但性能会更差:

SELECT *, (SELECT SUM(amount) FROM table WHERE date < @date GROUP BY DATE) AS total FROM table WHERE date < @date ORDER BY date;

答案 2 :(得分:0)

您想要检索并显示所有这些记录,不是吗?然后:
在您的PHP脚本中,您可以存储它“处理”的最后日期。如果下一个记录具有另一个日期值,则当前“组”结束 - &gt;打印当前总和,将其重置为零并存储新日期。打印当前记录,按amount增加$ sum。重复,直到没有更多记录。

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($pdo);

$prevDate = null;
$sum = 0;
foreach( $pdo->query('SELECT * FROM soFoo WHERE `date`<CURDATE() ORDER BY `date`', PDO::FETCH_ASSOC) as $row ) {
    if ( $prevDate!=$row['date'] ) {
        if ( !is_null($prevDate) ) {
            echo "-----------------\n", $sum, ' | ', $prevDate, "\n\n";
            $sum = 0;
        }
        $prevDate=$row['date'];
    }

    echo $row['amount'], ' | ', $row['date'], "\n";
    $sum += $row['amount'];
}


function setup($pdo) {
    $pdo->exec('CREATE TEMPORARY TABLE soFoo (
        id int auto_increment,
        amount Decimal(8,1),
        `date` Date,
        primary key(id)
    )');
    $pdo->exec("INSERT INTO soFoo (amount,`date`) VALUES
        (2.0, '2011-10-01'),
        (1.4, '2011-10-02'),
        (2.6, '2011-10-01'),
        (2.3, '2011-10-02'),
        (4.4, '2011-10-01'),
        (5.6, '2011-10-03'),
        (6.3, '2011-10-01')
    ");
}

打印

2.0 | 2011-10-01
2.6 | 2011-10-01
4.4 | 2011-10-01
6.3 | 2011-10-01
-----------------
15.3 | 2011-10-01

1.4 | 2011-10-02
2.3 | 2011-10-02
-----------------
3.7 | 2011-10-02

5.6 | 2011-10-03