【问题标题】:Calculate daily use from running total in c#从 C# 中的总使用量计算每日使用量
【发布时间】:2026-01-27 22:25:01
【问题描述】:

我有一个包含以下列的 sql 表,我正在尝试找到一种方法来自动计算每个条目的每日使用量。 'Total Usage' 是一个累计,每人每天一次。

最终我希望能够将其作为 c# 中的列表进行操作,但基于 sql 查询的方法也会很有用。这在 excel 中很容易做到,但我希望有一种方法可以自动化它......

Date  |  Name  |  Total Usage | Daily Usage

2016-01-01 | John | 60 | ?
2016-01-02 | John | 63 | ?
2016-01-03 | John | 66 | ?
2016-01-01 | Jane | 30 | ?
2016-01-02 | Jane | 50 | ?
2016-01-03 | Jane | 75 | ?

【问题讨论】:

  • 如果您可以将表格作为某种列表获取,则可以将 LINQ 与 table.Select(row => row.Column[2] / 365)from row in table select row.Column[2] / 365 之类的东西一起使用
  • 对于您问题中给出的数据,“总使用量”值是多少?
  • 总用水量
  • 您希望通过对每个人的“总使用量”值求和来获得每个人每天的每日使用量?

标签: c# sql-server-2012


【解决方案1】:

根据您的问题,您可以使用以下用 C# 编写的代码 sn-p 获取结果表,该代码利用 System.DataSystem.Data.SqlClient 对象库:

strSQL = "Select [Name], AVG([Total Usage]) As AvrUsage FROM [YourTableName] GROUP BY [Name]";
               // get data table with two columns: Name and AvgUsage
                using (SqlConnection _connSql = new SqlConnection(connString))
                {
                    using (SqlCommand _commandSql = new (SqlCommand())
                    {
                        _commandSql.CommandType = CommandType.Text;
                        _commandSql.Connection = _connSql;
                        _commandSql.CommandText = strSQL;
                        _connSql.Open();

                        using (SqlDataReader _drSql = _commandSql.ExecuteReader())
                        {
                            DataTable _dt = new DataTable();
                            _dt.Load(_drSql);
                            return _dt;
                        }
                    }
                }
            }
            catch (Exception ex) {
                throw; 
            }

,其中connString - 是您的 Sql 数据库的连接字符串。

或者,您可以应用SUM([Total Usage])/365,而不是AVG([Total Usage]),具体取决于您的特定需求定义。

希望这会有所帮助。

【讨论】: