datetime 필드가있는 logs라는 테이블이 있습니다. 특정 날짜 형식을 기반으로 날짜 및 행 수를 선택하고 싶습니다.날짜별로 SQLAlchemy의 특정 형식으로 그룹화
SQLAlchemy를 사용하여 어떻게합니까?
datetime 필드가있는 logs라는 테이블이 있습니다. 특정 날짜 형식을 기반으로 날짜 및 행 수를 선택하고 싶습니다.날짜별로 SQLAlchemy의 특정 형식으로 그룹화
SQLAlchemy를 사용하여 어떻게합니까?
SQLAlchemy를 알지 못하므로 오프 타겟이 될 수 있습니다.
SELECT date_formatter(datetime_field, "format-specification") AS dt_field, COUNT(*)
FROM logs
GROUP BY date_formatter(datetime_field, "format-specification")
ORDER BY 1;
확인, 어쩌면 당신이 ORDER BY를 필요로하지 않으며, 어쩌면 날짜 식을 다시 지정하는 것이 더 될 것이다 : 그러나, 나는 모두 당신이 필요하다고 생각합니다. 다음과 같은 대안이있을 수 있습니다.
SELECT dt_field, COUNT(*)
FROM (SELECT date_formatter(datetime_field, "format-specification") AS dt_field
FROM logs) AS necessary
GROUP BY dt_field
ORDER BY dt_field;
기타 등등. 기본적으로 datetime 필드의 서식을 지정한 다음 서식이 지정된 값에 대한 그룹화 등을 수행합니다.
포맷되지 않은 datetime 열로 그룹화 할 때 계산 결과가 동일합니까? 그렇다면 쿼리를 실행하고 나중에 파이썬 날짜의 strftime() 메소드를 사용할 수 있습니다. 즉
query = select([logs.c.datetime, func.count(logs.c.datetime)]).group_by(logs.c.datetime)
results = session.execute(query).fetchall()
results = [(t[0].strftime("..."), t[1]) for t in results]
일반 SQLAlchemy 답변을 모릅니다. 대부분의 데이터베이스는 일반적으로 함수를 통해 날짜 형식을 지원합니다. SQLAlchemy는 sqlalchemy.sql.func를 통해 함수 호출을 지원합니다. 포스트 그레스 백 엔드에 걸쳐 SQLAlchemy의 사용, 테이블 MY_TABLE (foo는 VARCHAR (30), 타임 스탬프) 나는 달립니다 날짜별로 그룹에 뭔가 같은
my_table = metadata.tables['my_table']
foo = my_table.c['foo']
the_date = func.date_trunc('month', my_table.c['when'])
stmt = select(foo, the_date).group_by(the_date)
engine.execute(stmt)
을 할 수있는, 그래서 예를 들면. 그러나이 예에서 date_trunc()는 Postgres datetime 함수입니다. 다른 데이터베이스는 다릅니다. Underlyig 데이터베이스는 언급하지 않았습니다. 데이터베이스를 독립적으로 수행 할 수있는 방법을 찾지 못했습니다. 제 경우에는 프로덕션을 실행하고 Postgres 및 단위 테스트 aggin SQLite를 테스트하고 단위 테스트에서 SQLite 사용자 정의 함수를 사용하여 Postgress datetime 함수를 에뮬레이트했습니다.
정확히 내가 필요로하는 .. 이제 SQLite 매뉴얼에 truncate 함수를 찾아야한다! 제 생각에는''STRFTIME ('% Y- % m', when)입니다. –