Symfony DQL:根据月份和年份对数据进行分组时,以月值获取null

时间:2016-05-17 15:41:55

标签: php symfony doctrine

这里没有显示月份,也没有根据月份对数据进行分组,我只是获取总金额或所有字段和空月值!,这是查询:

$em = $this->get("doctrine")->getManager();
        $conn = $em->getConnection();
        $sql = "SELECT MONTH(FROM_UNIXTIME(s.timestamp)) as mon, SUM(s.amt) as total FROM sales s GROUP BY MONTH(FROM_UNIXTIME(s.timestamp)) ORDER BY mon";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        $all_rows = $stmt->fetchAll();
        foreach ($all_rows as $row) {
            echo "Month: {$row["mon"]}, Total: {$row["total"]} \n";
        }

表值:

  1. 2016-05-26 00:00:00 - 150
  2. 2016-05-24 00:00:00 - 300
  3. 2016-05-26 00:00:00 - 250
  4. 2016-04-24 00:00:00 - 380
  5. 所以输出应该是: 月:4 amt:380 月:5 amt:700

    但得到:

      

    月:,amt:1080

    任何解决方案?

    谢谢。

1 个答案:

答案 0 :(得分:1)

由于您的日期存储为DateTime TYPE,因此可能不需要MySQL FROM_UNIXTIME()。我打赌这就是你想要做的事情:

<?php

    $this->get("doctrine")->getManager();
    $conn       = $em->getConnection();
    $sql        = "SELECT MONTH(s.timestamp) as mon, SUM(s.amt) as total FROM sales s GROUP BY MONTH(s.timestamp) ORDER BY MONTH(s.timestamp)";
    $stmt       = $conn->prepare($sql);
    $stmt->execute();

    $all_rows   = $stmt->fetchAll();

    foreach ($all_rows as $row) {
        echo "Month: {$row["mon"]}, Total: {$row["total"]} \n";
    }

以下是使用您首选语法(别名)的查询的较短变体...

<?php
    $this->get("doctrine")->getManager();
    $conn       = $em->getConnection();
    $sql        = "SELECT MONTH(s.timestamp) as mon, SUM(s.amt) as total FROM sales s GROUP BY mon ORDER BY mon";
    $stmt       = $conn->prepare($sql);
    $stmt->execute();

    $all_rows   = $stmt->fetchAll();

    foreach ($all_rows as $row) {
        echo "Month: {$row["mon"]}, Total: {$row["total"]} \n";
    }

以下是从Symfony3尝试转储的屏幕截图:

enter image description here

相关问题