我如何过滤出总和为零的数据集上的重复条目

时间:2019-02-19 21:29:12

标签: sql database postgresql duplicates

下面突出显示的是重复的数据,其具有不同的trip_total_amount。我希望他们摆脱查询结果,因为它们的总和等于零。

这是我获取此数据的查询:

SELECT * FROM efleet_copy AS e1
INNER JOIN
(SELECT mta_id, COUNT(mta_id) FROM efleet_copy WHERE EXTRACT(MONTH from service_date) = 02
  AND mta_id LIKE '_________'
 GROUP BY mta_id HAVING COUNT(mta_id) > 1) AS e2
ON e1.mta_id = e2.mta_id
WHERE EXTRACT(MONTH from service_date) = 02
ORDER BY e1.mta_id ASC, ride_id ASC, trip_number ASC;

data set

1 个答案:

答案 0 :(得分:2)

以这种方式尝试:

with cte0 as 
(
    SELECT * FROM efleet_copy AS e1
    INNER JOIN
    (SELECT mta_id, COUNT(mta_id) FROM efleet_copy WHERE EXTRACT(MONTH from service_date) = 02
      AND mta_id LIKE '_________'
     GROUP BY mta_id HAVING COUNT(mta_id) > 1) AS e2
    ON e1.mta_id = e2.mta_id
    WHERE EXTRACT(MONTH from service_date) = 02
    ORDER BY e1.mta_id ASC, ride_id ASC, trip_number ASC
)
SELECT * from cte0 c
WHERE not exists (
    SELECT 1 FROM CTE0 ci
    WHERE c.ride_id = ci.ride_id 
    GROUP BY ride_id 
    having sum(trip_total_amount) = 0 
)