Объединение двух запросов и вычисление результата - PullRequest
0 голосов
/ 26 мая 2020

Я пытаюсь вычислить разницу между запросом 1:

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 "Customer Investment"
from (
    select COUNT(*) as cnt
    from "mv_fundraiser_report"
    where thank_you_delivered = true
    [[AND {{NonProfit}}]]
    [[AND {{StartDate}}]]
    ) t

и запросом 2:

SELECT ((cast(A.TNUM as float)/cast(A.TDENOM as float))-(cast(A.FNUM as float)/cast(A.FDENOM as float)))*cast(A.TDENOM as float) AS "Heck"
FROM (SELECT
(SELECT SUM("public"."mv_fundraiser_report"."total_raised")
FROM "public"."mv_fundraiser_report"
WHERE ("public"."mv_fundraiser_report"."opt-in" = FALSE
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 704943916598630
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 193572775319413
AND NOT(first_name IS NULL
AND total_raised > 1000
AND fundraiser_type = 'Generic Fundraiser')
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]])) AS FNUM,

(SELECT count(*) AS "count"
FROM "public"."mv_fundraiser_report"
WHERE ("public"."mv_fundraiser_report"."opt-in" = FALSE
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 704943916598630
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 193572775319413
AND NOT(first_name IS NULL
AND total_raised > 1000
AND fundraiser_type = 'Generic Fundraiser')
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]])) AS FDENOM,

(SELECT SUM("public"."mv_fundraiser_report"."total_raised")
FROM "public"."mv_fundraiser_report"
WHERE ("public"."mv_fundraiser_report"."opt-in" = TRUE
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 704943916598630
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 193572775319413
AND NOT(first_name IS NULL
AND total_raised > 1000
AND fundraiser_type = 'Generic Fundraiser')
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]])) AS TNUM,

(SELECT count(*) AS "count"
FROM "public"."mv_fundraiser_report"
WHERE ("public"."mv_fundraiser_report"."opt-in" = TRUE
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 704943916598630
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 193572775319413
AND NOT(first_name IS NULL
AND total_raised > 1000
AND fundraiser_type = 'Generic Fundraiser')
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]])) AS TDENOM) A

Оба запроса работают сами по себе и возвращают одно число, но Я сильно борюсь с синтаксисом. Я совершенно не уверен, как я могу использовать (оконные?) Функции для достижения конечного результата. Любая помощь приветствуется, спасибо!

1 Ответ

1 голос
/ 26 мая 2020

Вы можете поместить каждый запрос в общие табличные выражения, а затем вычесть одно из другого.

Например (переработанный запрос 2 для упрощения):

WITH one AS (
  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 "Customer Investment"
  FROM (
      SELECT COUNT(*) as cnt
      FROM "mv_fundraiser_report"
      WHERE thank_you_delivered = true
      [[AND {{NonProfit}}]]
      [[AND {{StartDate}}]]
      ) t
),
two AS (
  SELECT (
            (
              SUM(public.mv_fundraiser_report.total_raised)
                FILTER (WHERE public.mv_fundraiser_report.opt-in = FALSE)
            )::float AS FNUM /
            (
              count(*)
                FILTER (WHERE public.mv_fundraiser_report.opt-in = FALSE)
            )::float AS FDENOM
          ) - 
          (
            (
              SUM(public.mv_fundraiser_report.total_raised)
                FILTER (WHERE public.mv_fundraiser_report.opt-in = TRUE)
            )::float AS TNUM /
            (
              count(*)
                FILTER (WHERE public.mv_fundraiser_report.opt-in = TRUE)
            )::float AS TDENOM
          ) AS "Heck"
  FROM public.mv_fundraiser_report
  WHERE NOT public.mv_fundraiser_report.campaign_id = 704943916598630
  AND NOT public.mv_fundraiser_report.campaign_id = 193572775319413
  AND NOT (first_name IS NULL
  AND total_raised > 1000
  AND fundraiser_type = 'Generic Fundraiser')
  AND [[{{NonProfit}}]]
  AND [[{{DateRange}}]])
)
SELECT one."Customer Investment" - two."Heck" AS difference
FROM one, two;

У меня нет ваши данные или схема, чтобы проверить это, поэтому это не проверено.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...