Amazon Redshift SQL - 工会

Amazon Redshift SQL - Unions

尽管尝试了几种不同的修复方法(包括此版本转换所有变量),但我在合并这三个支出查询时遇到了问题。

SELECT inside.date AS "date", CAST('facebook' AS varchar(20)) AS "ad_channel", 
  CAST(inside.ad_customer_group AS varchar(3)) AS "ad_customer_group", CAST(SUM(inside.ad_spend) AS integer) AS "ad_spend"
FROM
(
  SELECT CAST(TRUNC(FP.date) AS date) AS "date", CASE WHEN UPPER(SUBSTRING(adset_name,12,3)) = 'RTN' THEN 'RTN' ELSE 'ACQ' END AS "ad_customer_group", 
    CAST(SUM(spend) AS integer) AS "ad_spend"
  FROM public.fact_facebook_paid_placements FP
  GROUP BY CAST(TRUNC(FP.date) AS date), FP.adset_name
  ORDER BY CAST(TRUNC(FP.date) AS date) DESC
) AS "inside"
GROUP BY inside.date, inside.ad_customer_group
ORDER BY inside.date DESC

UNION ALL

SELECT CAST(TRUNC(timestamp) AS date) AS "date", CAST('google_ads' AS varchar(20)) AS "ad_channel", 
  CAST('ACQ' AS varchar(3)) AS "ad_customer_group", CAST(SUM(cost)) AS integer) AS "ad_spend"
FROM public.fact_adwords_ads
GROUP BY CAST(TRUNC(timestamp) AS date)
ORDER BY CAST(TRUNC(timestamp) AS date) DESC

UNION ALL

SELECT CAST(TRUNC(timestamp) AS date) AS "date", CAST('bing_ads' AS varchar(20)) AS "ad_channel", 
  CAST('ACQ' AS varchar(3)) AS "ad_customer_group", CAST(SUM(spend)) AS integer) AS "ad_spend"
FROM public.fact_bing_ad_performance
GROUP BY CAST(TRUNC(timestamp) AS date)
ORDER BY CAST(TRUNC(timestamp) AS date) DESC

如果您 post 在查询过程中遇到错误,那将是一个很大的帮助。但是我可以从你的查询中假设你得到了关于 GROUP BY 语句的错误,因为你只按第一列(和一个查询中的第二列)分组,并且没有在 group by 或 in 中使用其他列使用任何聚合函数

所以,我想这个查询会做你想做的事

(
SELECT
  CAST(TRUNC(FP.date) AS date) AS "date",
  CAST(CASE
    WHEN UPPER(SUBSTRING(adset_name,12,3)) = 'RTN' THEN 'RTN'
    ELSE 'ACQ'
  END AS varchar(3)) AS "ad_customer_group",
  SUM(spend) AS "ad_spend"
FROM public.fact_facebook_paid_placements FP
GROUP BY 1, 2, 3
ORDER BY 1 DESC
)

UNION ALL

(
SELECT
  CAST(TRUNC(timestamp) AS date) AS "date",
  CAST('google_ads' AS varchar(20)) AS "ad_channel",
  CAST('ACQ' AS varchar(3)) AS "ad_customer_group",
  SUM(cost) "ad_spend"
FROM public.fact_adwords_ads
GROUP BY 1, 2, 3
ORDER BY 1 DESC
)

UNION ALL

(
SELECT
  CAST(TRUNC(timestamp) AS date) AS "date", 
  CAST('bing_ads' AS varchar(20)) AS "ad_channel", 
  CAST('ACQ' AS varchar(3)) AS "ad_customer_group", 
  SUM(spend) AS "ad_spend"
FROM public.fact_bing_ad_performance
GROUP BY 1, 2, 3
ORDER BY 1 DESC
)