查询优化

master
tq 5 months ago
parent 2682bd343d
commit e86b8520dd

@ -106,7 +106,7 @@ ORDER BY
FROM
emeter_day_energy
WHERE
time >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
time >= DATE_FORMAT(NOW(), '%Y-%m-01')
AND type = {type}
GROUP BY
code

@ -15,175 +15,6 @@ public class EmeterEnergyChangeService : BaseServices<EmeterEnergyChange>
_emeterEnergyChangeRep = emeterEnergyChangeRep;
}
public async Task<List<EmeterEnergyChange>> SevenDaysElectrical()
{
// 根据code分组,取最近7天数据,每天最大值-最小值=当日用电量,如果当天目前只有一条数据,取当天最大值-前一天最大值=当天耗电量
string sql = @"
WITH daily_max_min AS (
SELECT
`code`,
DATE(`upload_time`) AS `UploadTime`,
MAX(`value`) AS `MaxValue`,
MIN(`value`) AS `MinValue`,
COUNT(*) AS `Count`
FROM
`emeter_energy_change`
WHERE
`upload_time` >= NOW() - INTERVAL 8 DAY
GROUP BY
`code`, DATE(`upload_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<EmeterEnergyChange> emeterEnergies = await _emeterEnergyChangeRep.SqlQueryable(sql);
return emeterEnergies;
}
public async Task<List<EmeterEnergyChange>> GetAllElectricalData()
{
string sql = @"
SELECT
code,
MAX(value) - MIN(value) AS Value
FROM
emeter_energy_change
WHERE
upload_time >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
GROUP BY
code
ORDER BY
code;
";
List<EmeterEnergyChange> emeterEnergies = await _emeterEnergyChangeRep.SqlQueryable(sql);
return emeterEnergies;
}
public async Task<List<EmeterEnergyChange>> GetTodayHourlyElectricalData()
{
string sql = @"
WITH hourly_max_min AS (
SELECT
`code`,
DATE_FORMAT(`upload_time`, '%Y-%m-%d %H:00:00') AS `Hour`,
MAX(`value`) AS `MaxValue`,
MIN(`value`) AS `MinValue`,
COUNT(*) AS `record_count`
FROM
`emeter_energy_change`
WHERE
DATE(`upload_time`) = CURDATE()
GROUP BY
`code`, DATE_FORMAT(`upload_time`, '%Y-%m-%d %H:00:00')
), previous_hour_max AS (
SELECT
`code`,
`Hour`,
LAG(`MaxValue`) OVER (PARTITION BY `code` ORDER BY `Hour`) AS `PreviousMaxValue`
FROM
`hourly_max_min`
)
SELECT
h.`code`,
h.`Hour`,
CASE
WHEN h.`record_count` > 1 THEN h.`MaxValue` - h.`MinValue`
ELSE h.`MaxValue` - COALESCE(p.`PreviousMaxValue`, 0)
END AS `Value`
FROM
`hourly_max_min` h
LEFT JOIN
`previous_hour_max` p ON h.`code` = p.`code` AND h.`Hour` = p.`Hour`
ORDER BY
h.`code`, h.`Hour`;
";
List<EmeterEnergyChange> emeterEnergies = await _emeterEnergyChangeRep.SqlQueryable(sql);
return emeterEnergies;
}
/// <summary>
/// 根据分钟统计电量
/// </summary>
/// <returns></returns>
public async Task<List<EmeterEnergyChange>> GetTodayMinutelyElectricalData()
{
string sql = @"
WITH minute_max_min AS (
SELECT
`code`,
DATE_FORMAT(`upload_time`, '%Y-%m-%d %H:%i:00') AS `Minute`,
MAX(`value`) AS `MaxValue`,
MIN(`value`) AS `MinValue`,
COUNT(*) AS `record_count`
FROM
`emeter_energy_change`
WHERE
`upload_time` >= NOW() - INTERVAL 1 HOUR
GROUP BY
`code`, DATE_FORMAT(`upload_time`, '%Y-%m-%d %H:%i:00')
), previous_minute_max AS (
SELECT
`code`,
`Minute`,
LAG(`MaxValue`) OVER (PARTITION BY `code` ORDER BY `Minute`) AS `PreviousMaxValue`
FROM
`minute_max_min`
)
SELECT
m.`code`,
m.`Minute`,
CASE
WHEN m.`record_count` > 1 THEN m.`MaxValue` - m.`MinValue`
WHEN p.`PreviousMaxValue` IS NULL THEN 0
ELSE m.`MaxValue` - p.`PreviousMaxValue`
END AS `Value`
FROM
`minute_max_min` m
LEFT JOIN
`previous_minute_max` p ON m.`code` = p.`code` AND m.`Minute` = p.`Minute`
ORDER BY
m.`code`, m.`Minute`;
";
List<EmeterEnergyChange> emeterEnergies = await _emeterEnergyChangeRep.SqlQueryable(sql);
return emeterEnergies;
}
/// <summary>
/// 获取交流电表实时数据
/// </summary>
@ -193,30 +24,14 @@ ORDER BY
// 将传入的时间参数转换为DateTime类型
DateTime endDateTime = DateTime.Parse(endTime);
// 根据传入的时间参数计算7天前的时间
DateTime startDateTime = endDateTime.AddDays(-7);
// 根据传入的时间参数计算1分钟的时间
DateTime startDateTime = endDateTime.AddMinutes(-1);
// 根据code分组,取最新时间的一条数据,数据范围7天
string sql = @"
SELECT t1.*
FROM emeter_energy_change t1
JOIN (
SELECT code, MAX(upload_time) as latest_upload_time
FROM emeter_energy_change
WHERE upload_time >= @StartDateTime AND upload_time <= @EndDateTime
GROUP BY code
) t2 ON t1.code = t2.code AND t1.upload_time = t2.latest_upload_time
WHERE t1.upload_time >= @StartDateTime AND t1.upload_time <= @EndDateTime;
";
// 使用参数化查询防止SQL注入
var parameters = new List<SugarParameter>
{
new SugarParameter("@StartDateTime", startDateTime),
new SugarParameter("@EndDateTime", endDateTime)
};
List<EmeterEnergyChange> list = await _emeterEnergyChangeRep.QueryListByClauseAsync(i => i.UploadTime>=startDateTime);
List<EmeterEnergyChange> emeterEnergyChanges = _emeterEnergyChangeRep.SqlQuery(sql, parameters);
return emeterEnergyChanges;
return list
.GroupBy(e => e.Code)
.Select(g => g.OrderByDescending(e => e.UploadTime).First())
.ToList();
}
}

@ -15,187 +15,6 @@ public class EmeterEnergyService : BaseServices<EmeterEnergy>
this.BaseDal = service;
}
/// <summary>
/// 获取七天用电量
/// </summary>
/// <returns></returns>
public async Task<List<EmeterEnergy>> SevenDaysElectrical()
{
// 根据code分组,取最近7天数据,每天最大值-最小值=当日用电量,如果当天目前只有一条数据,取当天最大值-前一天最大值=当天耗电量
string sql = @"
WITH daily_max_min AS (
SELECT
`code`,
DATE(`upload_time`) AS `UploadTime`,
MAX(`value`) AS `MaxValue`,
MIN(`value`) AS `MinValue`,
COUNT(*) AS `Count`
FROM
`emeter_energy`
WHERE
`upload_time` >= NOW() - INTERVAL 8 DAY
GROUP BY
`code`, DATE(`upload_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<EmeterEnergy> emeterEnergies = await this.BaseDal.SqlQueryable(sql);
return emeterEnergies;
}
/// <summary>
/// 获取全部用电量
/// </summary>
/// <returns></returns>
public async Task<List<EmeterEnergy>> GetAllElectricalData()
{
string sql = @"
SELECT
code,
MAX(value) - MIN(value) AS Value
FROM
emeter_energy
WHERE
upload_time >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
GROUP BY
code
ORDER BY
code;
";
List<EmeterEnergy> emeterEnergies = await this.BaseDal.SqlQueryable(sql);
return emeterEnergies;
}
/// <summary>
/// 根据小时统计电量
/// </summary>
/// <returns></returns>
public async Task<List<EmeterEnergy>> GetTodayHourlyElectricalData()
{
string sql = @"
WITH hourly_max_min AS (
SELECT
`code`,
DATE_FORMAT(`upload_time`, '%Y-%m-%d %H:00:00') AS `Hour`,
MAX(`value`) AS `MaxValue`,
MIN(`value`) AS `MinValue`,
COUNT(*) AS `record_count`
FROM
`emeter_energy`
WHERE
DATE(`upload_time`) = CURDATE()
GROUP BY
`code`, DATE_FORMAT(`upload_time`, '%Y-%m-%d %H:00:00')
), previous_hour_max AS (
SELECT
`code`,
`Hour`,
LAG(`MaxValue`) OVER (PARTITION BY `code` ORDER BY `Hour`) AS `PreviousMaxValue`
FROM
`hourly_max_min`
)
SELECT
h.`code`,
h.`Hour`,
CASE
WHEN h.`record_count` > 1 THEN h.`MaxValue` - h.`MinValue`
ELSE h.`MaxValue` - COALESCE(p.`PreviousMaxValue`, 0)
END AS `Value`
FROM
`hourly_max_min` h
LEFT JOIN
`previous_hour_max` p ON h.`code` = p.`code` AND h.`Hour` = p.`Hour`
ORDER BY
h.`code`, h.`Hour`;
";
List<EmeterEnergy> emeterEnergies = await this.BaseDal.SqlQueryable(sql);
return emeterEnergies;
}
/// <summary>
/// 根据分钟统计电量
/// </summary>
/// <returns></returns>
public async Task<List<EmeterEnergy>> GetTodayMinutelyElectricalData()
{
string sql = @"
WITH minute_max_min AS (
SELECT
`code`,
DATE_FORMAT(`upload_time`, '%Y-%m-%d %H:%i:00') AS `Minute`,
MAX(`value`) AS `MaxValue`,
MIN(`value`) AS `MinValue`,
COUNT(*) AS `record_count`
FROM
`emeter_energy`
WHERE
`upload_time` >= NOW() - INTERVAL 1 HOUR
GROUP BY
`code`, DATE_FORMAT(`upload_time`, '%Y-%m-%d %H:%i:00')
), previous_minute_max AS (
SELECT
`code`,
`Minute`,
LAG(`MaxValue`) OVER (PARTITION BY `code` ORDER BY `Minute`) AS `PreviousMaxValue`
FROM
`minute_max_min`
)
SELECT
m.`code`,
m.`Minute`,
CASE
WHEN m.`record_count` > 1 THEN m.`MaxValue` - m.`MinValue`
WHEN p.`PreviousMaxValue` IS NULL THEN 0
ELSE m.`MaxValue` - p.`PreviousMaxValue`
END AS `Value`
FROM
`minute_max_min` m
LEFT JOIN
`previous_minute_max` p ON m.`code` = p.`code` AND m.`Minute` = p.`Minute`
ORDER BY
m.`code`, m.`Minute`;
";
List<EmeterEnergy> emeterEnergies = await this.BaseDal.SqlQueryable(sql);
return emeterEnergies;
}
/// <summary>
/// 获取直流电表实时数据
/// </summary>
@ -205,30 +24,14 @@ ORDER BY
// 将传入的时间参数转换为DateTime类型
DateTime endDateTime = DateTime.Parse(endTime);
// 根据传入的时间参数计算7天前的时间
// 根据传入的时间参数计算1分钟的时间
DateTime startDateTime = endDateTime.AddMinutes(-1);
// 根据code分组,取最新时间的一条数据,数据范围7天
string sql = @"
SELECT t1.*
FROM emeter_energy t1
JOIN (
SELECT code, MAX(upload_time) as latest_upload_time
FROM emeter_energy
WHERE upload_time >= @StartDateTime AND upload_time <= @EndDateTime
GROUP BY code
) t2 ON t1.code = t2.code AND t1.upload_time = t2.latest_upload_time
WHERE t1.upload_time >= @StartDateTime AND t1.upload_time <= @EndDateTime;
";
// 使用参数化查询防止SQL注入
var parameters = new List<SugarParameter>
{
new SugarParameter("@StartDateTime", startDateTime),
new SugarParameter("@EndDateTime", endDateTime)
};
List<EmeterEnergy> list = await this.BaseDal.QueryListByClauseAsync(i => i.UploadTime>=startDateTime);
List<EmeterEnergy> emeterEnergies = this.BaseDal.SqlQuery(sql, parameters);
return emeterEnergies;
return list
.GroupBy(e => e.Code)
.Select(g => g.OrderByDescending(e => e.UploadTime).First())
.ToList();
}
}

@ -32,54 +32,6 @@ namespace Service.Ammeter
return Result<PageResult<EmeterHourEnergy>>.Success(PageResult<EmeterHourEnergy>.ConvertPage(this.BaseDal.QueryIPageByCause(queryPageModel1, null)));
}
/// <summary>
/// 根据小时统计电量
/// </summary>
/// <returns></returns>
public async Task<List<EmeterHourEnergy>> GetTodayHourlyElectricalData(int type)
{
string sql = $@"
WITH hourly_max_min AS (
SELECT
`code`,
DATE_FORMAT(`time`, '%Y-%m-%d %H:00:00') AS `Hour`,
MAX(`real_time_value`) AS `MaxValue`,
MIN(`real_time_value`) AS `MinValue`,
COUNT(*) AS `record_count`
FROM
`emeter_hour_energy`
WHERE
DATE(`time`) = CURDATE()
AND `type` = {type}
GROUP BY
`code`, DATE_FORMAT(`time`, '%Y-%m-%d %H:00:00')
), previous_hour_max AS (
SELECT
`code`,
`Hour`,
LAG(`MaxValue`) OVER (PARTITION BY `code` ORDER BY `Hour`) AS `PreviousMaxValue`
FROM
hourly_max_min
)
SELECT
h.`code`,
h.`Hour`,
CASE
WHEN h.`record_count` > 1 THEN h.`MaxValue` - h.`MinValue`
ELSE h.`MaxValue` - COALESCE(p.`PreviousMaxValue`, 0)
END AS `Value`
FROM
hourly_max_min h
LEFT JOIN
previous_hour_max p ON h.`code` = p.`code` AND h.`Hour` = p.`Hour`
ORDER BY
h.`code`, h.`Hour`;
";
List<EmeterHourEnergy> emeterEnergies = await this.BaseDal.SqlQueryable(sql);
return emeterEnergies;
}
/// <summary>
/// 获取直流电表实时数据

@ -32,54 +32,5 @@ namespace Service.Ammeter
return PageResult<EmeterMinutesEnergy>.ConvertPage(_emeterMinutesEnergyRepository1.QueryIPageByCause(queryPageModel1, null));
}
/// <summary>
/// 根据分钟统计电量
/// </summary>
/// <returns></returns>
public async Task<List<EmeterMinutesEnergy>> GetTodayMinutelyElectricalData(int type)
{
string sql = $@"
WITH minute_max_min AS (
SELECT
`code`,
DATE_FORMAT(`time`, '%Y-%m-%d %H:%i:00') AS `Minute`,
MAX(`real_time_value`) AS `MaxValue`,
MIN(`real_time_value`) AS `MinValue`,
COUNT(*) AS `record_count`
FROM
`emeter_minutes_energy`
WHERE
`time` >= NOW() - INTERVAL 1 HOUR
AND `type` = {type}
GROUP BY
`code`, DATE_FORMAT(`time`, '%Y-%m-%d %H:%i:00')
), previous_minute_max AS (
SELECT
`code`,
`Minute`,
LAG(`MaxValue`) OVER (PARTITION BY `code` ORDER BY `Minute`) AS `PreviousMaxValue`
FROM
minute_max_min
)
SELECT
m.`code`,
m.`Minute`,
CASE
WHEN m.`record_count` > 1 THEN m.`MaxValue` - m.`MinValue`
WHEN p.`PreviousMaxValue` IS NULL THEN 0
ELSE m.`MaxValue` - p.`PreviousMaxValue`
END AS `Value`
FROM
minute_max_min m
LEFT JOIN
previous_minute_max p ON m.`code` = p.`code` AND m.`Minute` = p.`Minute`
ORDER BY
m.`code`, m.`Minute`;
";
List<EmeterMinutesEnergy> emeterEnergies = await this.BaseDal.SqlQueryable(sql);
return emeterEnergies;
}
}
}

@ -87,7 +87,19 @@ public class CountDayOrderJob : AbstractCronJob
dayCount.ToltalSwapAllTime = Math.Round(totalMinutes, 2);
dayCount.State = StaticStationInfo.StationStatus;
var dateTime = DateTime.Now;
var formattedDateTime = dateTime.ToString("yyyy-MM-dd HH:mm");
// 查询当前分钟的数据
var existingData = _ExStationDayRunResultService.QueryListByClause(i =>
i.CreatedTime.HasValue && formattedDateTime.Equals(i.CreatedTime.Value.ToString("yyyy-MM-dd HH:mm")));
if (!existingData.Any())
{
_ExStationDayRunResultService.Insert(dayCount);
}
return Task.CompletedTask;
}

@ -32,43 +32,31 @@ public class EmeterDayJob: AbstractCronJob
List<EmeterEnergyChange> emeterEnergiesChange = _EmeterEnergyChangeRepository.QueryListByClause(i =>
dateTime.Equals(i.UploadTime.ToString("yyyy-MM-dd")), "upload_time desc");
List<EmeterDayEnergy> db = new List<EmeterDayEnergy>();
if (emeterEnergies.Count > 0)
{
Dictionary<string, List<EmeterEnergy>> dictionary =
emeterEnergies.GroupBy(i => i.Code).ToDictionary(i => i.Key, i => i.ToList());
List<EmeterDayEnergy> list = new List<EmeterDayEnergy>();
foreach (var keyValuePair in dictionary)
{
EmeterDayEnergy emitterDayEnergy = new EmeterDayEnergy();
emitterDayEnergy.Code = keyValuePair.Key;
emitterDayEnergy.Time = dateTime;
emitterDayEnergy.Type = 1;
EmeterEnergy? maxValue = keyValuePair.Value.MaxBy(x => x.Value);
EmeterEnergy? minValue = keyValuePair.Value.MinBy(x => x.Value);
if (maxValue != null)
{
emitterDayEnergy.RealTimeValue = maxValue.Value;
}
if (maxValue != null && minValue != null)
{
emitterDayEnergy.Value = maxValue.Value - minValue.Value;
}
list.Add(emitterDayEnergy);
var value = keyValuePair.Value;
var orderByDescending = value.OrderByDescending(i => i.UploadTime).ToList();
emitterDayEnergy.RealTimeValue = orderByDescending[0].Value;
emitterDayEnergy.Value = orderByDescending[0].Value -
orderByDescending[^1].Value;
db.Add(emitterDayEnergy);
}
_EmeterDayEnergyRepository.Insert(list);
}
if (emeterEnergiesChange.Count > 0)
{
Dictionary<string, List<EmeterEnergyChange>> dictionaryChange =
emeterEnergiesChange.GroupBy(i => i.Code).ToDictionary(i => i.Key, i => i.ToList());
List<EmeterDayEnergy> list = new List<EmeterDayEnergy>();
foreach (var keyValuePair in dictionaryChange)
{
@ -76,25 +64,23 @@ public class EmeterDayJob: AbstractCronJob
emitterDayEnergy.Code = keyValuePair.Key;
emitterDayEnergy.Time = dateTime;
emitterDayEnergy.Type = 2;
EmeterEnergyChange? maxValue = keyValuePair.Value.MaxBy(x => x.Value);
EmeterEnergyChange? minValue = keyValuePair.Value.MinBy(x => x.Value);
if (maxValue != null)
{
emitterDayEnergy.RealTimeValue = maxValue.Value;
var value = keyValuePair.Value;
var orderByDescending = value.OrderByDescending(i => i.UploadTime).ToList();
emitterDayEnergy.RealTimeValue = orderByDescending[0].Value;
emitterDayEnergy.Value = orderByDescending[0].Value -
orderByDescending[^1].Value;
db.Add(emitterDayEnergy);
}
if (maxValue != null && minValue != null)
{
emitterDayEnergy.Value = maxValue.Value - minValue.Value;
}
list.Add(emitterDayEnergy);
if (db.Count > 0)
{
var existingData = _EmeterDayEnergyRepository.QueryListByClause(i =>
dateTime.Equals(i.Time));
if (!existingData.Any())
{
_EmeterDayEnergyRepository.Insert(db);
}
_EmeterDayEnergyRepository.Insert(list);
}
return Task.CompletedTask;

@ -77,9 +77,14 @@ public class EmeterHourJob : AbstractCronJob
}
if (db.Count > 0)
{
var existingData = _EmeterHourEnergy.QueryListByClause(i =>
dateTime.Equals(i.Time));
if (!existingData.Any())
{
_EmeterHourEnergy.Insert(db);
}
}
return Task.CompletedTask;
}

@ -82,9 +82,14 @@ public class EmeterMinuteJob : AbstractCronJob
}
if (db.Count > 0)
{
var existingData = EmeterMinutesEnergyRepository.QueryListByClause(i =>
dateTime.Equals(i.Time));
if (!existingData.Any())
{
EmeterMinutesEnergyRepository.Insert(db);
}
}
Log.Info($"EmeterMinuteJob execute end ");

@ -1,4 +1,5 @@
using AutoMapper;
using System.Linq.Expressions;
using AutoMapper;
using Entity.Ammeter;
using Entity.Api.Resp;
using HybirdFrameworkCore.Entity;
@ -97,25 +98,37 @@ namespace WebStarter.Controllers.Ammeter
[HttpGet("GetLastDayMeterData")]
public async Task<Result<List<EmeterEnergyTimeResp>>> GetLastDayMeterData()
{
// 获取最近一天直流和交流表数据
var daysElectricalTask = _emeterHourEnergyService.GetTodayHourlyElectricalData(1);
var daysElectricalChangeTask = _emeterHourEnergyService.GetTodayHourlyElectricalData(2);
DateTime todayZero = DateTime.Today;
await Task.WhenAll(daysElectricalTask, daysElectricalChangeTask);
List<EmeterHourEnergy> list = await _emeterHourEnergyService.QueryListByClauseAsync(i => DateTime.Parse(i.Time)>=todayZero);
var daysElectrical = daysElectricalTask.Result;
var daysElectricalChange = daysElectricalChangeTask.Result;
List<EmeterHourEnergy> daysElectrical = list.Where(i => i.Type == 1).ToList();
var config = new MapperConfiguration(cfg =>
List<EmeterHourEnergy> daysElectricalChange = list.Where(i => i.Type == 2).ToList();
List<EmeterResp> energyList = new List<EmeterResp>();
foreach (var energy in daysElectrical)
{
cfg.CreateMap<EmeterResp, EmeterHourEnergy>().ReverseMap();
});
var mapper = config.CreateMapper();
EmeterResp resp = new EmeterResp();
resp.Code = energy.Code;
resp.Value = energy.Value;
resp.Hour = energy.Time;
energyList.Add(resp);
}
var energyList = mapper.Map<List<EmeterResp>>(daysElectrical);
energyList?.ForEach(emeterResp => emeterResp.Type = 0);
var energyChangeList = mapper.Map<List<EmeterResp>>(daysElectricalChange);
List<EmeterResp> energyChangeList = new List<EmeterResp>();
foreach (var energy in daysElectricalChange)
{
EmeterResp resp = new EmeterResp();
resp.Code = energy.Code;
resp.Value = energy.Value;
resp.Hour = energy.Time;
energyChangeList.Add(resp);
}
energyChangeList?.ForEach(emeterResp => emeterResp.Type = 1);
var respList = new List<EmeterEnergyTimeResp>();
@ -157,30 +170,6 @@ namespace WebStarter.Controllers.Ammeter
return Result<List<EmeterEnergyTimeResp>>.Success(respList, "成功");
}
/// <summary>
/// 直流电能表小时统计
/// </summary>
/// <returns></returns>
[HttpGet("GetTodayHourlyEnergy")]
public async Task<Result<List<EmeterHourEnergy>>> GetTodayHourlyElectricalData()
{
// 直流表数据
return Result<List<EmeterHourEnergy>>.Success(await _emeterHourEnergyService.GetTodayHourlyElectricalData(1), "成功");
}
/// <summary>
/// 交流电能表小时统计
/// </summary>
/// <returns></returns>
[HttpGet("GetTodayHourlyEnergyChange")]
public async Task<Result<List<EmeterHourEnergy>>> GetTodayHourlyElectricalChangeData()
{
// 交流表数据
return Result<List<EmeterHourEnergy>>.Success(
await _emeterHourEnergyService.GetTodayHourlyElectricalData(2), "成功");
}
/// <summary>
/// 最近一小时电表数据
/// </summary>
@ -188,29 +177,42 @@ namespace WebStarter.Controllers.Ammeter
[HttpGet("GetTodayMinutelyElectricalData")]
public async Task<Result<List<EmeterEnergyTimeResp>>> GetTodayMinutelyElectricalData()
{
// 获取最近一个小时直流和交流表数据
var minutesElectricalTask = _emeterMinutesEnergyService.GetTodayMinutelyElectricalData(1);
var minutesElectricalChangeTask = _emeterMinutesEnergyService.GetTodayMinutelyElectricalData(2);
await Task.WhenAll(minutesElectricalTask, minutesElectricalChangeTask);
DateTime now = DateTime.Now;
DateTime time = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0);
var minutesElectrical = minutesElectricalTask.Result;
var minutesElectricalChange = minutesElectricalChangeTask.Result;
List<EmeterMinutesEnergy> list = await _emeterMinutesEnergyService.QueryListByClauseAsync(i => DateTime.Parse(i.Time)>=time);
var config = new MapperConfiguration(cfg =>
List<EmeterMinutesEnergy> daysElectrical = list.Where(i => i.Type == 1).ToList();
List<EmeterMinutesEnergy> daysElectricalChange = list.Where(i => i.Type == 2).ToList();
List<EmeterResp> energyList = new List<EmeterResp>();
foreach (var energy in daysElectrical)
{
cfg.CreateMap<EmeterResp, EmeterMinutesEnergy>().ReverseMap();
});
var mapper = config.CreateMapper();
EmeterResp resp = new EmeterResp();
resp.Code = energy.Code;
resp.Value = energy.Value;
resp.Minute = energy.Time;
energyList.Add(resp);
}
var energyList = mapper.Map<List<EmeterResp>>(minutesElectrical);
// 类型赋值直流
energyList?.ForEach(emeterResp => emeterResp.Type = 0);
var energyChangeList = mapper.Map<List<EmeterResp>>(minutesElectricalChange);
// 类型赋值交流
List<EmeterResp> energyChangeList = new List<EmeterResp>();
foreach (var energy in daysElectricalChange)
{
EmeterResp resp = new EmeterResp();
resp.Code = energy.Code;
resp.Value = energy.Value;
resp.Minute = energy.Time;
energyChangeList.Add(resp);
}
energyChangeList?.ForEach(emeterResp => emeterResp.Type = 1);
var respList = new List<EmeterEnergyTimeResp>();
var groupedEnergyList = energyList
@ -257,31 +259,64 @@ namespace WebStarter.Controllers.Ammeter
[HttpGet("GetEnergyMeterRealTime")]
public async Task<Result<EmeterEnergyResp>> GetEnergyMeterRealTime(string endTime)
{
// 不传值时查实时
if (!DateTime.TryParse(endTime, out DateTime parsedEndTime))
EmeterEnergyResp resp = new EmeterEnergyResp();
DateTime parsedEndTime;
if (!DateTime.TryParse(endTime, out parsedEndTime))
{
parsedEndTime = DateTime.Now;
endTime = parsedEndTime.ToString("yyyy-MM-dd HH:mm:ss");
await QueryRealTime(resp,endTime);
}
else
{
endTime = parsedEndTime.ToString("yyyy-MM-dd HH:mm:ss");
await QueryParameterTime(resp, endTime);
}
// 获取实时直流和交流表数据
List<EmeterHourEnergy> minutesElectrical = await _emeterHourEnergyService.GetEnergyMeterRealTime(endTime, 1);
List<EmeterHourEnergy> minutesElectricalChange = await _emeterHourEnergyService.GetEnergyMeterRealTime(endTime, 2);
return Result<EmeterEnergyResp>.Success(resp, "成功");
}
EmeterEnergyResp resp = new EmeterEnergyResp
private async Task QueryRealTime(EmeterEnergyResp resp,string time)
{
emeterEnergy = TransformEnergyData(minutesElectrical, 0),
emeterEnergyChange = TransformEnergyData(minutesElectricalChange, 1)
};
List<EmeterEnergy> sevenDaysElectrical = await _emeterEnergyService.GetEnergyMeterRealTime(time);
List<EmeterEnergyChange> emeterEnergyChanges = await _emeterEnergyChangeService.GetEnergyMeterRealTime(time);
return Result<EmeterEnergyResp>.Success(resp, "成功");
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<EmeterResp, EmeterEnergy>().ReverseMap();
cfg.CreateMap<EmeterResp, EmeterEnergyChange>().ReverseMap();
});
IMapper mapper = config.CreateMapper();
resp.emeterEnergy = MapEnergyData(mapper.Map<List<EmeterResp>>(sevenDaysElectrical), 0);
resp.emeterEnergyChange = MapEnergyData(mapper.Map<List<EmeterResp>>(emeterEnergyChanges), 1);
}
private async Task QueryParameterTime(EmeterEnergyResp resp, string endTime)
{
List<EmeterHourEnergy> minutesElectrical =
await _emeterHourEnergyService.GetEnergyMeterRealTime(endTime, 1);
List<EmeterHourEnergy> minutesElectricalChange =
await _emeterHourEnergyService.GetEnergyMeterRealTime(endTime, 2);
resp.emeterEnergy = TransformEnergyData(minutesElectrical, 0);
resp.emeterEnergyChange = TransformEnergyData(minutesElectricalChange, 1);
}
private List<EmeterResp> MapEnergyData(List<EmeterResp> energyData, int type)
{
energyData?.ForEach(emeterResp => emeterResp.Type = type);
return energyData?.OrderBy(e => e.Code).ToList();
}
private List<EmeterResp> TransformEnergyData(List<EmeterHourEnergy> energyData, int type)
{
return energyData.Select(hourEnergy =>
{
DateTime? uploadTime = DateTime.TryParse(hourEnergy.Time, out DateTime parsedTime) ? parsedTime : (DateTime?)null;
DateTime? uploadTime = DateTime.TryParse(hourEnergy.Time, out DateTime parsedTime)
? parsedTime
: (DateTime?)null;
return new EmeterResp
{
@ -293,6 +328,7 @@ namespace WebStarter.Controllers.Ammeter
}).OrderBy(e => e.Code).ToList();
}
private static void ElectricEnergyDay(List<EmeterDayEnergy> daysElectrical, List<EmeterDayEnergy> emeterEnergyChanges, EmeterEnergyResp resp)
{
var config = new MapperConfiguration(cfg =>

Loading…
Cancel
Save