【发布时间】:2021-08-24 15:03:32
【问题描述】:
我在下面创建了一个 sql,当我试图将它放在外部选择下时,它将只显示从下面的 WITH 子句查询呈现的结果,它在 sql server 中给了我错误,在那里工作正常与甲骨文。 我不想创建一个视图,我想把它放在合并语句中的输出下面...
select custno, slipno, category, donation, unique_nm from
(
-- Here it is throwing error
with got_debit_custno (custno, slipno, category, donation, debit_custno) as
(
select custno, slipno, category, donation
, case
when category = 'CREDIT'
then 'N/A'
else custno
end
from a
)
, prep (custno, slipno, category, donation, debit_custno, rn, rdt) as
(
select dc.*
, row_number () over (partition by debit_custno, category order by donation, slipno)
, sum (donation) over (partition by debit_custno, category order by donation, slipno)
from got_debit_custno dc
)
, r (custno, slipno, category, donation, debit_custno, rn, rdt, mn) as
(
select custno, slipno, category, donation, debit_custno
, case
when rn = max(rn) over (partition by debit_custno, category)
then rn
end
, rdt, 1
from prep
where rdt <= 27000 or rn = 1
union all
select p.custno, p.slipno, p.category, p.donation, p.debit_custno
, case
when p.rn = max(p.rn) over (partition by p.debit_custno, p.category)
then p.rn
end
, p.rdt, r.mn + 1
from prep p
join r on p.debit_custno = r.debit_custno
and p.category = r.categoRy
and p.rn > r.rn
and (p.rdt <= r.rdt + 27000 or p.rn = r.rn + 1)
)
select custno, slipno, category, donation
, dense_rank () over (order by debit_custno, category, mn) as unique_nm
from r)
order by custno, unique_nm, donation
【问题讨论】:
-
WITH位于语句的开头,而不是定义 CTE 时的中间。你不是SELECT...FROM (WITH {CTE Definition}),而是WITH {CTE Definition} ... SELECT ...FROM {CTE Name}。见WITH common_table_expression (Transact-SQL)
标签: sql sql-server tsql sql-server-2012 common-table-expression