按日分组和部分SQL

时间:2016-10-14 16:11:03

标签: mysql sql

我希望每天都能获得销售统计数据,并计算出哪个部分销售了多少。

我真的很困惑"一切"。

$em = $this->getEntityManager()->getConnection();

$stmt = $em->prepare("
        SELECT
            COUNT(o.id) AS `all`,
            (
              SELECT COUNT(id) FROM order_panoramic_orders WHERE DAY(created_at) = DAY(NOW()) AND status_id NOT IN (7,9)
            ) AS `day`
        FROM
          order_panoramic_orders as o
        WHERE
         status_id NOT IN (7,9)
        ");

我可以获得每日统计数据,但我不知道如何处理部分分离。

结果必须与此类似:

  

Day:1 - Total:10 - Section1:3,Section2:5,Section3:2

有什么想法吗?

顺便说一句;

分区和用户表是分开的。

我想,我必须加入这两张表。

第一张表:订单 第二个表:用户 第三表:部分

1 个答案:

答案 0 :(得分:1)

奇怪的查询。您的查询应该只是条件聚合。不需要子查询:

SELECT COUNT(*) AS `all`,
       SUM(DAY(created_at) = DAY(NOW())) as day
FROM order_panoramic_orders o
WHERE status_id NOT IN (7, 9);

然后,您可以使用相同的想法获取部分:

SELECT COUNT(*) AS `all`,
       SUM(DAY(created_at) = DAY(NOW())) as day,
       SUM(section = 1) as section1,
       SUM(section = 2) as section2,
       SUM(section = 3) as section3
FROM order_panoramic_orders o
WHERE status_id NOT IN (7, 9);