我有以下的peewee表/类(在postgres DB上)和虚线下面的一个我喜欢的例子。
基本上我是在数据库查询中完成newb并且不知道如何构建它:我需要,给出一个日期列表(例如[' 2015-01-01',... ])获取每天警报的数量(如果有的话)作为每个服务的计数。希望下面的例子足够清楚。
class Event(BaseModel):
assessment = CharField(max_length = 4096)
day = DateField()
ongoing = BooleanField()
alertType = CharField(null = True)
links = CharField(null = True, max_length = 4096)
newLinks = CharField(null = True, max_length = 4096)
startTime = TimeField()
endTime = TimeField(null = True)
class Service(BaseModel):
svcid = TextField(unique = True)
name = TextField()
class Alert(BaseModel):
alertId = CharField(unique = True, null = True)
alertLink = CharField(unique = True, null = True)
startTime = TimeField()
endTime = TimeField(null = True)
jcaLink = CharField(max_length = 4096, null = True)
description = CharField(max_length = 4096)
relatedNodes = CharField(null = True)
customerName = CharField(null = True)
jcaUrl = CharField(null = True)
deviceName = CharField(null = True)
event = ForeignKeyField(Event, related_name = 'alerts')
service = ForeignKeyField(Service, related_name = 'alerts')
hosted = CharField(default = None, null = True)
------------------------------------------------------------
Example: Event.id 1 has Event.day '2015-01-01'
Event.id 2 has Event.day '2015-01-02'
Service.id 1 has name "A"
Service.id 2 has name "B"
Alert.id 1 has Alert.event.id 1, Alert.service.id 1
Alert.id 2 has Alert.event.id 2, Alert.service.id 2
Alert.id 3 has Alert.event.id 2, Alert.service.id 1
# end of db
If days is ['2015-01-01', '2015-01-02'], output should be like (not resembling, just broken up/organized somewhat like)
Service A
day 2015-01-01
1 alert
day 2015-01-02
1 alert
-----------------
Service B
day 2015-01-01
1 alert
day 2015-01-02
0 alerts
答案 0 :(得分:0)
这应该这样做。我不确定你的模型是否添加了像s.id
这样的列,但我想它确实如此。你的start_time是一个时间字段,所以我使用date()
方法,所以我们只是比较日期部分。
select s.name, date(a.start_time) as alert_date, count(s.name) as alerts
from alert a join service s on a.service_id = s.id
where date(a.start_time) in ('2015-01-01', '2015-01-02')
group by s.name, alert_date
请注意,在执行分组时,所有选定的字段必须在group by或aggregate函数中使用。有办法解决这个问题,但由于你需要这么少的数据,所以我不认为service.name
是唯一的。
此外,如果您希望按月,年等方式收到提醒,则可以使用extract
,如下所示:
select s.name, extract(month from a.start_time) as alert_month,
extract(year from a.start_time) as alert_year, count(s.name) as alerts
from alert a join service s on a.service_id = s.id
where extract(year from a.start_time) = 2015
and extract(month from a.start_time) in (11, 12)
group by s.name, alert_month, alert_year