douliang1891 2014-08-03 18:43
浏览 42
已采纳

SQL:我可以在GROUP BY查询中获取别名吗?

I have this query:

SELECT date, sum(money) as total
    FROM gasto 
    GROUP BY date;

The table in question has two fields: date (where the input is a specific day), and money (an integer).

To print out the sums, for each day, I do this:

$resultado=mysqli_query($conectar,$consulta); //this is to get the result
foreach ($resultado as $key => $value) {
    echo $key.' - '.$value['total'].'<br>';

This results in:

0 - 20

1 - 45

2 - 12

etc.

My question is, how do I print out each date right before the aumont?

  • 写回答

2条回答 默认 最新

  • dongyu4908 2014-08-03 18:52
    关注

    Try this:

    $resultado=mysqli_query($conectar,$consulta); //this is to get the result
    foreach ($resultado as $key => $value) {
        echo $key.' - '. $value['date'] . ' : ' . $value['total'].'<br>';    
    }
    

    Your selected table names will not change with group by.

    You also can do this if you want to give an alias:

    //SELECT date as mydate, sum(money) as total FROM gasto GROUP BY date;
    $resultado=mysqli_query($conectar,$consulta); //this is to get the result
    foreach ($resultado as $key => $value) {
        echo $key.' - '. $value['mydate'] . ' : ' . $value['total'].'<br>';    
    }
    

    For the future you can do print_r($resultado) to see, what you get from your database fetch method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应