2017-11-03 4 views
1

다음 관계가있는 특성에 대해이 쿼리를 작성하고 있습니다.중첩 쿼리에서 "그룹화 기준"을 두 번 피하는 방법

State->City->Customer->Service Order. 

모든 일대 다. 하위 쿼리는 svc_ord_nbr으로 그룹화하여 집계하며 외부 쿼리는 다른 집계에서 다른 집계를 수행합니다.

select state, city, cust_name, 
    count(distinct (case when start_date <> end_date then svc_ord_nbr end)) as not_fixed 
    from 
    (SELECT svc_ord_nbr, CUST_NAME, 
     state, city, 
     date_trunc('day', min(START_DTM)) as start_date, 
     date_trunc('day', max(START_DTM)) as end_date 
     FROM table a inner join... 
      inner join.... 
    WHERE ...... 
    group by SVC_ORD_NBR, 
    cust_name, 
    state, 
    city) q 
    group by state, city, cust_name 

주와시를 표시하려면 내부 쿼리와 외부 쿼리에서 두 번 그룹화해야합니다. 이것이 최선의 방법인지 궁금합니다.

+0

@GordonLinoff는'date_trunc'를 사용해야했습니다 – ddd

+0

'inner join ....':: 일부 메타 구문이 아닌 실제 쿼리를 게시하십시오. – wildplasser

+0

작업별로 내부 그룹과 외부 그룹의 SVC_ORD_NBR이 같은 순서로 나열된 열이있는 경우 성능이 향상 될 수 있습니다. –

답변

0

svc_ord_nbr로 MIN/MAX를 계산했기 때문에 "2 개의 레이어"를 피할 수 있다고 생각하지 않습니다. 그 다음 계산을 위해이 계산을 사용합니다. 예를 들어 내부 레이어의 svc_ord_nbr 만 처리하면 조금 더 간단해질 수 있습니다. 내가 볼 수

SELECT 
     state 
    , city 
    , cust_name 
    , COUNT(DISTINCT (CASE WHEN start_date <> end_date THEN svc_ord_nbr END) 
      ) AS not_fixed 
FROM (
     SELECT 
      svc_ord_nbr 
      , date_trunc('day', MIN(START_DTM)) AS start_date 
      , date_trunc('day', MAX(START_DTM)) AS end_date 
     FROM tablea a 
     WHERE ...... 
     GROUP BY 
      svc_ord_nbr 
    ) q 
inner join... 
inner join.... 
GROUP BY 
     state 
    , city 
    , cust_name 
+0

질문이 지금 해결 되었습니까? 이 답변에 대해 질문이 있습니까? [help/accepting] (https://stackoverflow.com/help/someone-answers)에 대한 자세한 내용은 "[** 클릭 **] (https://ibb.co/ikqyO6)"대답을 수락하려면 –

0

하나의 단순화는 외부 수준에서 count(distinct) 제거지고 있습니다. 대신 당신이 단지 수 있습니다

select state, city, cust_name, 
     sum((start_date <> end_date)::int) as not_fixed 
. . . 

는 집계의 두 가지 수준을 제거 할 수 있습니다 특별한 경우가있을 수 있습니다, 나는 일반적인 솔루션 생각할 수 없다.

관련 문제