如何避免"分组"在嵌套查询中两次

时间:2017-11-03 19:03:14

标签: sql postgresql group-by subquery

我正在为具有以下关系的属性编写此查询。

 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

为了显示州和城市,似乎我必须在内部和外部查询中将它们分组两次。我想知道这是否是最佳方式。

2 个答案:

答案 0 :(得分:0)

我不认为你可以避免做&#34; 2层&#34;因为您正在通过svc_ord_nbr计算MIN / MAX,然后将这些计算用于后续计数。您可以通过仅处理内层中的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

答案 1 :(得分:0)

我能看到的一个简化就是摆脱外层的count(distinct)。相反,你可以这样做:

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

可能有一些特殊情况,你可以摆脱两个级别的聚合,我想不出一般的解决方案。