我找到了替换Oracle的“CONNECT BY LEVEL”in this question的基本答案,但我的情况稍微复杂一些:
基本上我要替换的东西是这样的:
...
UNION ALL
Select
adate, 'ROAD' as TSERV_ID, 0 AS EQ_NBR
from
(SELECT
to_date(sysdate - 732,'dd/mm/yy') + rownum -1 as adate, rownum
FROM
(select rownum
from dual
connect by level <= 732)
WHERE rownum <= 732)
UNION ALL
Select
adate, 'PORTPACK' as TSERV_ID, 0 AS EQ_NBR
from
(SELECT
to_date(sysdate - 732,'dd/mm/yy') + rownum -1 as adate, rownum
FROM
(select rownum from dual connect by level <= 732)
WHERE rownum <= 732)
UNION ALL
....
现在,单个双连接很容易,即使这显然不是非常有效的方法
WITH CTE AS (
SELECT dateadd(day,-720,CONVERT (date, GETDATE())) as Datelist
UNION ALL
SELECT dateadd(day,1,Datelist)
FROM CTE
WHERE datelist < getdate() )
SELECT *,'ROAD' as Tserv_ID , 0 as EQ_NBR FROM CTE
option (maxrecursion 0)
重复联盟很难,因为我收到错误:
关键字'with'附近的语法不正确。如果此语句是公用表表达式,xmlnamespaces子句或更改跟踪上下文子句,则必须以分号结束前一个语句。
我在这里提供了这个联盟的更多部分;我只是在开始时尝试使用“WITH”但没有运气。我错过了一些明显的东西吗?
编辑:当然有一个很大的问题为什么我甚至试图做这样的事情:就个人而言,我不会,但在查询的另一端有一个巨大的Crystal Report每个月运行一次并接受这种特殊格式的数据。 FULL查询输出的结尾类似于3 columns of data
3 Columns of data
...
Currentdate-732,"ROAD",0
Currentdate -731,"ROAD",0
...
Currentdate, "ROAD,"0"
Currentdate -732, "PORTPAK", 0
Currentdate -731, "PORTPAK", 0
等
答案 0 :(得分:2)
你想做什么:
WITH CTE1 AS (...),
CTE2 AS (...)
SELECT stuff FROM CTE1
UNION ALL
SELECT stuff FROM CTE2;
?这是一个常见的挑战,我想这是不可发现的,为了使用多个CTE,你只需用逗号分隔它们。
大家都这么说,看起来你只想创造一系列日期。递归CTE(从不介意其中许多系列)并不是最有效的方法。而不是告诉我们你想要替换CONNECT BY LEVEL并向我们展示你尝试过的语法,为什么不显示或描述你想要的输出呢?我们已经了解到你已经尝试过自己的东西了(谢谢!)但我们宁愿给你一个有效的解决方案,而不是把差距缩小到低效率。
作为一个例子,这里需要一个很多少冗余代码的东西,并且(认为为你提供了你所追求的东西:
DECLARE @n INT = 722, @d DATE = CURRENT_TIMESTAMP;
;WITH v AS (SELECT v FROM (VALUES('ROAD'),('PORTPACK')) AS v(v)),
n AS (SELECT TOP (@n) n = ROW_NUMBER() OVER (ORDER BY number)
FROM master.dbo.spt_values ORDER BY n)
SELECT Datelist = DATEADD(DAY, 2-n.n, @d), Tserv_ID = v.v, EQ_NBR = 0
FROM n CROSS JOIN v
ORDER BY Tserv_ID, Datelist;