按组计算两组行之间的差异

时间:2020-06-01 18:20:02

标签: postgresql

在我的查询中,我有两个单独的查询(通过UNION ALL连接在一起),每个查询返回约40行。这是我的查询内容:

select case 
        when cnt >= 1 AND cnt <= 2000 then cnt * 6
        when cnt >= 2001 AND cnt <= 4000 then ((cnt - 2000) * 5) + 12000
        when cnt >= 4001 AND cnt <= 6000 then ((cnt - 4000) * 4) + 22000
        when cnt >= 6001 AND cnt <= 8000 then ((cnt - 6000) * 3) + 30000
        when cnt >= 8001 then ((cnt - 8000) * 2) + 36000
        else 1
        end "Number", ngo_name
from (
    select COUNT(*) as cnt, ngo_name
    from "mv_fundraiser_report"
    where thank_you_delivered = true
    GROUP BY ngo_name
    ) t

UNION ALL

select
  COALESCE((((NULLIF(cast(sum(case when "opt-in" is true AND NOT(first_name IS NULL AND total_raised > 1000 AND fundraiser_type = 'Generic Fundraiser') then "total_raised" else 0 end) as float), 0))
  /
  (NULLIF(cast(sum(case when "opt-in" is true AND NOT(first_name IS NULL AND total_raised > 1000 AND fundraiser_type = 'Generic Fundraiser') then 1 else 0 end) as float), 0)))
  -
  ((NULLIF(cast(sum(case when "opt-in" is false AND NOT(first_name IS NULL AND total_raised > 1000 AND fundraiser_type = 'Generic Fundraiser') then "total_raised" else 0 end) as float), 0))
  /
  (NULLIF(cast(sum(case when "opt-in" is false AND NOT(first_name IS NULL AND total_raised > 1000 AND fundraiser_type = 'Generic Fundraiser') then 1 else 0 end) as float), 0))))
  *
  (NULLIF(cast(sum(case when "opt-in" is true AND NOT(first_name IS NULL AND total_raised > 1000 AND fundraiser_type = 'Generic Fundraiser') then 1 else 0 end) as float), 0)), 0) AS "Number", ngo_name
from mv_fundraiser_report
[[where {{DateRange}}]]
group by ngo_name
ORDER BY ngo_name DESC

当我运行此查询时,这就是我收到的数据如下:

Organization|Number
Org1.       |1000
Org1.       |5000
Org2.       |2000
Org2.       |6000
Org3.       |10000
Org3.       |20000
Org4.       |13000
Org4.       |54000

我想做的是减去第一个查询和第二个查询之间的差异。我该如何计算两行之间的差异?

0 个答案:

没有答案