我的模型有点像
class ServiceUtilization(models.Model):
device_name = models.CharField()
service_name = models.CharField()
data_source = models.CharField()
current_value = models.CharField()
sys_timestamp = models.IntegerField()
现在,这里current_value
表示存储为 VarChar 的 Float 中的值,以及存储为 unixtime 的时间
在尝试获取 Max 和 Average 值时,current_value
我得到了意想不到的结果,因为对于 Max,MySQL 会进行基于字符串的比较,其中'100' value < '9.99'
在 Float 中采用了不正确的 wrt 值。
我试过了 :
perf = ServiceUtilization.objects.filter(
device_name__in=devices,
service_name__in=services,
data_source__in=data_sources,
sys_timestamp__gte=start_date,
sys_timestamp__lte=end_date
).values(
'device_name',
'service_name',
'data_source'
).annotate(
max_val=Max('current_value'),
avg_val=Avg('current_value')
)
它提供了不正确的结果。
然后看:HOW select min from cast varchar to int in mysql
我考虑过提供查询集extra
perf = ServiceUtilization.objects.extra(
select={
'max_val': "MAX(CAST(current_value AS SIGNED))",
'avg_val': "AVG(CAST(current_value AS SIGNED))"
}
).filter(
device_name__in=devices,
service_name__in=services,
data_source__in=data_sources,
sys_timestamp__gte=start_date,
sys_timestamp__lte=end_date
).values(
'device_name',
'service_name',
'data_source',
'max_val',
'avg_val'
)
但这只是提供了一个单一的价值,而不是想要的结果。这转换为 SQL
SELECT (MAX(CAST(current_value AS SIGNED))) AS `max_val`, (AVG(CAST(current_value AS SIGNED))) AS `avg_val`, `performance_utilizationstatus`.`device_name`, `performance_utilizationstatus`.`service_name`, `performance_utilizationstatus`.`data_source`
从performance_utilizationstatus
订购performance_utilizationstatus
。sys_timestamp
降序;
但是工作代码需要一个 GROUP BY on (device_name, service_name, data_source)
SELECT (MAX(CAST(current_value AS SIGNED))) AS `max_val`, (AVG(CAST(current_value AS SIGNED))) AS `avg_val`, `performance_utilizationstatus`.`device_name`, `performance_utilizationstatus`.`service_name`, `performance_utilizationstatus`.`data_source` FROM `performance_utilizationstatus`
分组依据performance_utilizationstatus
。device_name
, performance_utilizationstatus
. service_name
,
performance_utilizationstatus
. data_source
订购方式performance_utilizationstatus
。sys_timestamp
降序;
如何添加 GROUP BY CLAUSE ?
在这里使用annotate
不起作用
1111, 'Invalid use of group function'
或者
ERROR 1056 (42000): Can't group on 'max_val'
RAW SQL 会是最后的手段吗?