简体   繁体   English

选择按天分组的列值总和

[英]select with sum of column values grouping by day

I have a table with columns datetime, order value, and number of pieces for each order issued. 我有一个表,其中包含列日期时间,订单值和每个已发布订单的件数。 Datetime is in standard datetime mysql format. Datetime是标准的datetime mysql格式。

To get the total sum of orders, I have a query like this: 为了获得订单的总和,我有一个类似这样的查询:

$sqlsum = "SELECT SUM(order_value) FROM orders";
if (mysqli_query($conn, $sqlsum)) {
    $resultsum = mysqli_query($conn, $sqlsum);
    while($row = mysqli_fetch_assoc($resultsum)) {
        $total_sales = $row['SUM(order_value)'];

        // and here I use the value in a simple report
    }
}

To get a report of all single orders, usually I'd do like this: 为了获得所有单笔订单的报告,通常我会这样:

<?php

$sql = "SELECT * FROM orders";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        $order_time = $row["datetime"];
        $order_value = $row["order_value"];
        $pieces_number = $row["pieces"];

        // and here I use the results in a detailed report
    }
}
?>

Now I have to make two different reports, one for each day and one for each month, and each one has to show: 现在,我必须制作两个不同的报告,每天一个,每个月一个,并且每个报告都必须显示:
- count of orders -订单数
- sum of order values -订单价值之和
- sum of number of pieces -件数之和
How should be the query to get the count of orders per day and the sum of values and pieces per day? 查询应该如何获取每天的订单计数以及每天的价值和件数之和?

Googled the site for similar issues, but didn't find a post with a clear solution for my needs. Google在该网站上搜索了类似的问题,但没有找到满足我需要的明确解决方案的帖子。

In the 1st case you need to group by day using the DATE() function: 在第一种情况下,您需要使用DATE()函数按天分组:

SELECT 
  DATE(datetime) day, 
  COUNT(*) orderscounter,
  SUM(order_value) valuesum,
  SUM(pieces) piecessum
FROM orders
GROUP BY day

In the 2nd case you need to group by year/month using the YEAR() and MONTH() functions: 在第二种情况下,您需要使用YEAR()MONTH()函数按年/月分组:

SELECT 
  YEAR(datetime) year,
  MONTH(datetime) month, 
  COUNT(*) orderscounter,
  SUM(order_value) valuesum,
  SUM(pieces) piecessum
FROM orders
GROUP BY year, month

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM