使用SQL GROUP BY从每小时数据到每日数据

时间:2017-08-03 10:50:23

标签: sql group-by

我有一张这样的表:

fld_id          fld_DateTime                 fld_Index
            2017-07-01 00:00:00.000             5
            2017-07-01 01:00:00.000             10
            2017-07-01 02:00:00.000             15
            2017-07-01 03:00:00.000             40
              ...........
              ...........
            2017-07-01 23:00:00.000             70
            2017-07-02 00:00:00.000             110
            2017-07-02 01:00:00.000             140
            2017-07-02 02:00:00.000             190
              ...............
              ...............
            2017-07-02 23:00:00.000             190

我想要做的是将它们分组并每天计算fld_index的总和,如下所示:

  fld_id          fld_DateTime                    SUM
                  2017-07-01                      190
                  2017-07-02                      400

以下是我尝试的内容:

   SELECT fld_dateTime, SUM(fld_Index) AS Sum
FROM tbl_data
WHERE
    AND fld_ConsDateTime BETWEEN '2017-07-01' AND '2017-08-02'
GROUP BY fld_dateTime

它计算总和但仍以小时格式计算。如何实现上述示例的日常格式?

更新每月零件输出

2017    8   30630800.0000
2017    7   589076201.1800

2 个答案:

答案 0 :(得分:5)

简单地投射为DATE

SELECT CAST(fld_dateTime AS DATE) AS  fld_Date, SUM(fld_Index) AS Sum
FROM tbl_data
WHERE
   fld_ConsDateTime BETWEEN '2017-07-01' AND '2017-08-02'
GROUP BY CAST(fld_dateTime AS DATE);

修改

  

月份怎么样?这是逻辑吗?

这取决于您的RDBMS,但在SQL Server中您可以使用:

SELECT YEAR(fld_dateTime), MONTH(fld_dateTime), SUM(fld_Index) AS Sum
FROM tbl_data
GROUP BY YEAR(fld_dateTime), MONTH(fld_dateTime);

添加年份部分以避免对不同年份的记录进行分组非常重要。

答案 1 :(得分:3)

您需要提取日期。在SQL Server中,您可以这样做:

bWidget->setParent(aWidget);
cWidget->setParent(aWidget);

在MySQL中,上述方法可行,但我会这样做:

ui_*.h

在这两种情况下,您都应该更改 SELECT CAST(fld_dateTime as DATE) as fld_date, SUM(fld_Index) AS Sum FROM tbl_data WHERE fld_ConsDateTime >= '2017-07-01' AND fld_ConsDateTime < '2017-08-03' GROUP BY CAST(fld_dateTime as DATE) ORDER BY fld_date 子句。您的版本将保留2017-08-02日期/时间正好是午夜的航班。使用 SELECT DATE(fld_dateTime) as fld_date, SUM(fld_Index) AS Sum FROM tbl_data WHERE fld_ConsDateTime >= '2017-07-01' AND fld_ConsDateTime < '2017-08-03' GROUP BY DATE(fld_dateTime) ORDER BY fld_date; WHERE更准确 - 在一天内完成所有日期/时间,而不是下一天。