从2个查询中减去结果

时间:2019-10-25 21:37:56

标签: postgresql

我有2个查询,它们给出相同的结果(相同的列,行),但数据不同。我需要将结果从查询1的一列减去到查询2的同一列。

这是我的查询

QUERY 1

SELECT 
COUNT(DISTINCT CASE WHEN customer.ref IN ('emp', 'oth') THEN customer.id END) as visit_count, locations.name
FROM visits 
LEFT JOIN customer ON customer.id = visits.id
LEFT JOIN locations ON customer.loc_id = locations.id
WHERE visits.group_id = 1
GROUP BY locations.name, locations.id;

RESULTS
visit_count  |   location
---------------------------
      5      |    loc1
      1      |    loc2
      1      |    loc3

QUERY 2

SELECT COUNT(customer.id) as visit_count, locations.name FROM locations 
LEFT JOIN visits ON locations.name = visits.location_check
LEFT JOIN customer ON visits.cust_id = customer.id AND customer.group_id = 1
WHERE locations.group_id = 1 AND locations.active = true
GROUP BY locations.location_name, locations.id;

RESULTS
visit_count  |   location
---------------------------
      10      |    loc1
      15      |    loc2
      18      |    loc3

结果是相同的,我只需要从第二个结果中减去第一个结果。所以我想要的结果是:

visit_count  |   location
---------------------------
      5      |    loc1
      14     |    loc2
      17     |    loc3

有没有办法将它们连接在一起并从另一列中减去一列?

1 个答案:

答案 0 :(得分:2)

这是最直接的答案:

SELECT b.visit_count-a.visit_count, a.location
FROM
(
  SELECT 
  COUNT(DISTINCT CASE WHEN customer.ref IN ('emp', 'oth') THEN customer.id END) as visit_count, locations.name
  FROM visits 
  LEFT JOIN customer ON customer.id = visits.id
  LEFT JOIN locations ON customer.loc_id = locations.id
  WHERE visits.group_id = 1
  GROUP BY locations.name, locations.id;
) as a
(
  SELECT COUNT(customer.id) as visit_count, locations.name FROM locations 
  LEFT JOIN visits ON locations.name = visits.location_check
  LEFT JOIN customer ON visits.cust_id = customer.id AND customer.group_id = 1
  WHERE locations.group_id = 1 AND locations.active = true
  GROUP BY locations.location_name, locations.id;
) as b
WHERE a.location=b.location;

这显然只是您提供的内容的复制/粘贴,但是似乎需要消除一些细节,例如一个查询中的customer.id = visits.id和另一查询中的customer.id = visits.cust_id

您似乎想获得每个位置的总访问次数,减去customer.refempoth的访问次数。如果是这样,我想你只是想要这样的东西:

SELECT count(*), l.name as location
FROM visits v
JOIN customer c ON c.id=v.id
JOIN locations l ON l.id=c.loc_id
WHERE v.group_id = 1
AND l.active
AND c.ref NOT IN ('emp','oth')
GROUP BY l.name;

当然,正确查询取决于您的表结构,此处的列名似乎不一致,因此我们在这里实际上并不知道。

披露:我为EnterpriseDB (EDB)工作