我有一个完美运行的(顶部查询),但是我试图添加第二个查询来使用它,它所做的只是计算每天的总和。我对编写SQL还是比较陌生,我想知道是否有人可以帮助您完成这项工作?我尝试使用UNION,但不断查询块的结果列数不正确
提前谢谢!
Select POSTING_DATE,
MISTI_ID,
MATERIAL,
CASE
WHEN MTL_DESC IS NULL THEN
SHORT_TEXT
ELSE
MTL_DESC
END AS MTL_DESC,
VEND_NAME1,
RECIPIENT,
QTY,
AMT_GRP_CURR
From COST_DM5_DAILY
Where COST_CENTER = 'C1003'
ORDER BY POSTING_DATE DESC
这是第二个查询
Select SUM(AMT_GRP_CURR), Posting_date
From COST_DM5_DAILY
Where COST_CENTER = 'C1003'
group by Posting_date
order by Posting_date desc
答案 0 :(得分:0)
该错误表明UNION中使用的列数和数据类型必须匹配。看一下这个简单的例子:
在第二col2
中缺少select
:
SQL> select 100 col1, 'a' col2 from dual
2 union
3 select 300 col1 from dual;
select 100 col1, 'a' col2 from dual
*
ERROR at line 1:
ORA-01789: query block has incorrect number of result columns
第二个col2
中的select
数据类型错误:
SQL> select 100 col1, 'a' col2 from dual
2 union
3 select 300 col1, sysdate from dual;
select 100 col1, 'a' col2 from dual
*
ERROR at line 1:
ORA-01790: expression must have same datatype as corresponding expression
最后,要走的路:
SQL> select 100 col1, 'a' col2 from dual
2 union
3 select 300 col1, 'b' col2 from dual;
COL1 C
---------- -
100 a
300 b
SQL>
在您的代码中,看来您无法做到这一点-至少,这是没有意义的,因为您必须GROUP BY
所有列中使用未汇总的SELECT
列列表:
select posting_date,
misti_id,
material,
case
when mtl_desc is null then short_text
else mtl_desc
end as mtl_desc,
vend_name1,
recipient,
qty,
amt_grp_curr,
--
sum(amg_grp_curr) sum_result
from cost_dm5_daily
where cost_center = 'C1003'
group by
posting_date,
misti_id,
material,
case
when mtl_desc is null then short_text
else mtl_desc
end as mtl_desc,
vend_name1,
recipient,
qty,
amt_grp_curr
order by posting_date desc;
也许SUM
函数的解析形式可能会有所帮助。例如:
select posting_date,
misti_id,
material,
case
when mtl_desc is null then short_text
else mtl_desc
end as mtl_desc,
vend_name1,
recipient,
qty,
amt_grp_curr,
--
sum(amg_grp_curr) over(partition by posting_date order by null) sum_result
from cost_dm5_daily
where cost_center = 'C1003'
order by posting_date desc;
答案 1 :(得分:0)
您的第一个查询的结果集中有8列,而第二个查询只有2列;解释错误信息。第一个还具有date列,这是第二个问题-列的数据类型必须在每个位置都匹配(或至少可以隐式转换)。
您需要在第二个查询中交换列的顺序(因此日期排在第一位),然后确定您希望在哪个位置求和-并为其余部分添加空值(可能;或其他固定值)。
Select POSTING_DATE,
MISTI_ID,
MATERIAL,
CASE
WHEN MTL_DESC IS NULL THEN
SHORT_TEXT
ELSE
MTL_DESC
END AS MTL_DESC,
VEND_NAME1,
RECIPIENT,
QTY,
AMT_GRP_CURR
From COST_DM5_DAILY
Where COST_CENTER = 'C1003'
union all
Select Posting_date,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
SUM(AMT_GRP_CURR)
From COST_DM5_DAILY
Where COST_CENTER = 'C1003'
group by Posting_date
order by Posting_date desc;
您可能想要order by
中的其他字词,因为在同一日期您将有多个。
这可能是您的应用程序/报告层应该做的事情。