• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

장고 Queryset 질문이요.

20.05.29 10:51 작성 조회수 90

0

저희 회사 개발자분이 그만둬서,, 제가 이 강의를 아직 듣지는 못했지만 질문 남깁니다.

부서의 매출합계 * 100 / 전체 매출합계로 해서 비중(%)를 구하려고 하는데요.

Mariadb(MySQL)기준으로

SUM(`매출테이블`.매출컬럼) * 100 / SUM(SUM(`매출테이블`.매출컬럼)) OVER() as PER

이러한 컬럼인데요.

제 쿼리셋은

queryset = Sale.objects.all().select_related().values(
).annotate(
dept_nm=F('Department__dept_nm'),
dept_cd=F('Department__dept_cd'),
sal_year=ExtractYear('sal_dt'),
sal_month=ExtractMonth('sal_dt'),
sal_famt=F('sal_famt'),
).values(
'sal_year', 'dept_cd', 'dept_nm'
).annotate(
Jan=Coalesce(Sum(Case(When(sal_month=1, then='sal_famt'),)), 0),
Feb=Coalesce(Sum(Case(When(sal_month=2, then='sal_famt'),)), 0),
Mar=Coalesce(Sum(Case(When(sal_month=3, then='sal_famt'),)), 0),
Apl=Coalesce(Sum(Case(When(sal_month=4, then='sal_famt'),)), 0),
May=Coalesce(Sum(Case(When(sal_month=5, then='sal_famt'),)), 0),
Jun=Coalesce(Sum(Case(When(sal_month=6, then='sal_famt'),)), 0),
Jul=Coalesce(Sum(Case(When(sal_month=7, then='sal_famt'),)), 0),
Aug=Coalesce(Sum(Case(When(sal_month=8, then='sal_famt'),)), 0),
Sep=Coalesce(Sum(Case(When(sal_month=9, then='sal_famt'),)), 0),
Oct=Coalesce(Sum(Case(When(sal_month=10, then='sal_famt'),)), 0),
Nov=Coalesce(Sum(Case(When(sal_month=11, then='sal_famt'),)), 0),
Dec=Coalesce(Sum(Case(When(sal_month=12, then='sal_famt'),)), 0),
Tot=Coalesce(Sum('sal_famt'), 0),
).filter(sal_year=year).order_by('dept_cd')

현재 이런 구조입니다.

Queryset 결과는  dept_nm, dept_cd, sal_year, Jan ~ Dec, Tot 으로 나오구요.

비중(합계)를 MariaDB에서는 Sum() Over()를 쳤는데. 장고 Queryset에서는 어떻게 해야 할까요?

답변 1

답변을 작성해보세요.

0

이 부분은 강의에서 다루는 내용은 아니지만 아래 링크의 내용을 참고하셔서 annotate와 values, Sum 등을 활용하시면 될 거 같습니다.

https://stackoverflow.com/questions/37851053/django-query-group-by-month