using Entity.Ammeter; using Entity.Dto.Req; using HybirdFrameworkCore.Autofac.Attribute; using HybirdFrameworkCore.Entity; using Repository.Ammeter; using SqlSugar; namespace Service.Ammeter { /// /// /// [Scope("SingleInstance")] public class EmeterDayEnergyService : BaseServices { public EmeterDayEnergyService(EmeterDayEnergyRepository service) { this.BaseDal = service; } public async Task> Page(PageAmmeterReq queryPageModel) { QueryPageModel queryPageModel1 = new QueryPageModel { PageNum = queryPageModel.PageNum, PageSize = queryPageModel.PageSize, }; if (!string.IsNullOrEmpty(queryPageModel.Code)) return PageResult.ConvertPage(this.BaseDal.QueryIPageByCause(queryPageModel1, u => u.Code == queryPageModel.Code)); else return PageResult.ConvertPage(this.BaseDal.QueryIPageByCause(queryPageModel1, null)); } /// /// 获取七天用电量 /// /// public async Task> SevenDaysElectrical(int type) { // 根据code分组,取最近7天数据,每天最大值-最小值=当日用电量,如果当天目前只有一条数据,取当天最大值-前一天最大值=当天耗电量 string sql = $@" WITH daily_max_min AS ( SELECT `code`, DATE(`time`) AS `UploadTime`, MAX(`real_time_value`) AS `MaxValue`, MIN(`real_time_value`) AS `MinValue`, COUNT(*) AS `Count` FROM `emeter_day_energy` WHERE `time` >= NOW() - INTERVAL 8 DAY AND `type` = {type} GROUP BY `code`, DATE(`time`) ), previous_day_max AS ( SELECT `code`, `UploadTime`, `MaxValue`, `MinValue`, `Count`, LAG(`MaxValue`) OVER (PARTITION BY `code` ORDER BY `UploadTime`) AS `PreviousMaxValue` FROM daily_max_min ), daily_consumption AS ( SELECT d.`code`, d.`UploadTime`, CASE WHEN d.`Count` > 1 THEN d.`MaxValue` - d.`MinValue` WHEN d.`Count` = 1 AND d.`PreviousMaxValue` IS NOT NULL THEN d.`MaxValue` - d.`PreviousMaxValue` ELSE 0 END AS `DailyValue` FROM previous_day_max d WHERE d.`UploadTime` >= NOW() - INTERVAL 7 DAY ) SELECT `UploadTime`, SUM(`DailyValue`) AS `Value` FROM daily_consumption GROUP BY `UploadTime` ORDER BY `UploadTime`; "; List emeterEnergies = await this.BaseDal.SqlQueryable(sql); return emeterEnergies; } /// /// 获取全部用电量 /// /// public async Task> GetAllElectricalData(int type) { string sql = $@" SELECT code, MAX(real_time_value) - MIN(real_time_value) AS Value FROM emeter_day_energy WHERE time >= DATE_SUB(NOW(), INTERVAL 1 MONTH) AND type = {type} GROUP BY code ORDER BY code; "; List emeterEnergies = await this.BaseDal.SqlQueryable(sql); return emeterEnergies; } } }