簡體   English   中英

附加兩個表 - Union不在SQL中工作(Teradata)

[英]Append two tables - Union not working in SQL (Teradata)

我是SQL的初學者。 我正在使用Teradata。 我們試圖將數據匯總在一起,以比較實際值與預測值。

這是我的代碼:

select 
'Actuals' as fc_version,
A.tra_fiscal_year as fiscal_year,
A.tra_fiscal_week as fiscal_week,
A.tra_allocation_category_code as category,
A.tra_grand_pricing_sales_channel as grandparent_channel,
D.fc_prod_id,
coalesce(
case
when A.tra_ticket_product_code like 'A%' then 'Total'
else null
end,

case
when A.tra_grand_pricing_sales_channel = 'INMKT' Then 'In Market'
else 'All Other'
end )
as fc_sales_channel,

sum(A.tra_ticket_quantity) as units_sold,

from ((pd_plan_forecast_db.adm_rev_detail A
left outer join
pd_plan_forecast_db.adm_rev_prod_code_to_fc_id B
on (A.tra_ticket_product_code = B.product_code))
left outer join
pd_plan_forecast_db.adm_rev_ticket_code_to_fc_id C
on (A.tra_ticket_code = C.ticket_code)
left outer join
pd_plan_forecast_db.adm_rev_fc_prod_info D
on (coalesce(B.fc_prod_id, C.fc_prod_id) = D.fc_prod_id))

group by 1, 2, 3, 4, 5, 6, 7

union

select fc_version, fiscal_year, fiscal_week, category, null as grandparent_channel, fc_prod_id, fc_sales_channel, sum(units_sold) as units_sold
from pd_plan_forecast_db.adm_rev_fc
where fiscal_year = 2017 and fiscal_week = 1
group by 1,2,3,4,5,6,7

如果將第一部分粘貼到聯合之前,則它具有正確的結果。 同樣是工會后的第二部分。

但是整個代碼一起給出了錯誤:SELECT失敗。 [3654]相應的選擇列表表達式是不兼容的。

這是我正在使用的表的一般概念。 在此輸入圖像描述

您必須在兩個部分(頂部和底部)以及相同的數據類型中具有相同數量的列。

據我所知,頂部查詢中有9列,底部查詢中有8列。

UPD :根據作者的修復在下面的查詢中將null轉換為空字符串。

您應該在兩個選擇中具有相同數量的列,並且(在選擇中數字似乎為8)但是
在你的聯盟中,你不應該在第二個選擇中使用別名

select 
'Actuals' as fc_version,
A.tra_fiscal_year as fiscal_year,
A.tra_fiscal_week as fiscal_week,
A.tra_allocation_category_code as category,
A.tra_grand_pricing_sales_channel as grandparent_channel,
D.fc_prod_id,
coalesce(
case
when A.tra_ticket_product_code like 'A%' then 'Total'
else null
end,

case
when A.tra_grand_pricing_sales_channel = 'INMKT' Then 'In Market'
else 'All Other'
end )
as fc_sales_channel,

sum(A.tra_ticket_quantity) as units_sold,

from ((pd_plan_forecast_db.adm_rev_detail A
left outer join
pd_plan_forecast_db.adm_rev_prod_code_to_fc_id B
on (A.tra_ticket_product_code = B.product_code))
left outer join
pd_plan_forecast_db.adm_rev_ticket_code_to_fc_id C
on (A.tra_ticket_code = C.ticket_code)
left outer join
pd_plan_forecast_db.adm_rev_fc_prod_info D
on (coalesce(B.fc_prod_id, C.fc_prod_id) = D.fc_prod_id))

group by 1, 2, 3, 4, 5, 6, 7

union

select 
    fc_version
    , fiscal_year
    , fiscal_week
    , category
    , null 
    , fc_prod_id
    , fc_sales_channel
    , sum(units_sold) 
from pd_plan_forecast_db.adm_rev_fc
where fiscal_year = 2017 and fiscal_week = 1
group by 1,2,3,4,5,6,7

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM