programing

Common Table Expressions에 대해 중첩된 WITH 절을 만들 수 있습니까?

lastcode 2023. 4. 7. 21:27
반응형

Common Table Expressions에 대해 중첩된 WITH 절을 만들 수 있습니까?

WITH y AS (
    WITH x AS (
        SELECT * FROM MyTable
    )
    SELECT * FROM x
)
SELECT * FROM y

이런 게 효과가 있나요?아까 해봤는데 안 되더라고요.

엄밀하게 중첩되지는 않지만 공통 테이블 식을 사용하여 후속 쿼리에서 이전 쿼리를 재사용할 수 있습니다.

이를 위해 찾고 있는 스테이트먼트의 형식은 다음과 같습니다.

WITH x AS 
(
    SELECT * FROM MyTable
), 
y AS 
(
    SELECT * FROM x
)
SELECT * FROM y

다음을 수행할 수 있습니다. 이를 재귀 쿼리라고 합니다.

WITH y
AS
(
  SELECT x, y, z
  FROM MyTable
  WHERE [base_condition]

  UNION ALL

  SELECT x, y, z
  FROM MyTable M
  INNER JOIN y ON M.[some_other_condition] = y.[some_other_condition]
)
SELECT *
FROM y

이 기능은 필요하지 않을 수 있습니다.질문을 더 잘 정리하기 위해 다음 작업을 수행했습니다.

WITH y 
AS
(
  SELECT * 
  FROM MyTable
  WHERE [base_condition]
),
x
AS
(
  SELECT * 
  FROM y
  WHERE [something_else]
)
SELECT * 
FROM x

With는 내장되어 있지 않지만 연속적으로 동작합니다.

;WITH A AS(
...
),
B AS(
...
)
SELECT *
FROM A
UNION ALL
SELECT *
FROM B

편집 구문 수정...

또, 다음의 예도 봐 주세요.

SQLFiddle 데모

이러한 답변은 매우 좋지만, 상품을 올바르게 주문하는 한 이 기사를 보는 것이 좋습니다.http://dataeducation.com/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge

여기 그의 질문의 예가 있습니다.

WITH paths AS ( 
    SELECT 
        EmployeeID, 
        CONVERT(VARCHAR(900), CONCAT('.', EmployeeID, '.')) AS FullPath 
    FROM EmployeeHierarchyWide 
    WHERE ManagerID IS NULL

    UNION ALL

    SELECT 
        ehw.EmployeeID, 
        CONVERT(VARCHAR(900), CONCAT(p.FullPath, ehw.EmployeeID, '.')) AS FullPath 
    FROM paths AS p 
        JOIN EmployeeHierarchyWide AS ehw ON ehw.ManagerID = p.EmployeeID 
) 
SELECT * FROM paths order by FullPath

네스트된 cte를 생성할 수 있습니다.아래 cte의 예를 참조해 주세요.

;with cte_data as 
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)

select * from cte_data,cte_data1

시작과 종료 사이에 여러 프로세스가 있는 하나의 엔트리를 제외하고 이벤트 간의 시간을 측정하려고 했습니다.다른 단일 라인 프로세스의 맥락에서 이것이 필요했습니다.

Nth cte 내에서 내부 조인(inner join)이 있는 셀렉트를 선택문으로 사용했습니다.두 번째 cte는 X의 시작일과 Y의 종료일을 추출하여 1을 왼쪽 조인 ID 값으로 사용하여 한 줄에 놓았습니다.

도움이 됐으면 좋겠네요

cte_extract
as 
(
    select ps.Process as ProcessEvent
        , ps.ProcessStartDate 
        , ps.ProcessEndDate 
        -- select strt.*
    from dbo.tbl_some_table ps 
    inner join (select max(ProcessStatusId) ProcessStatusId 
                    from dbo.tbl_some_table 
                where Process = 'some_extract_tbl' 
                and convert(varchar(10), ProcessStartDate, 112) < '29991231'
                ) strt on strt.ProcessStatusId = ps.ProcessStatusID
), 
cte_rls
as 
(
    select 'Sample' as ProcessEvent, 
     x.ProcessStartDate, y.ProcessEndDate  from (
    select 1 as Id, ps.Process as ProcessEvent
        , ps.ProcessStartDate 
        , ps.ProcessEndDate
        -- select strt.*
    from dbo.tbl_some_table ps 
    inner join (select max(ProcessStatusId) ProcessStatusId 
                    from dbo.tbl_some_table 
                where Process = 'XX Prcss' 
                and convert(varchar(10), ProcessStartDate, 112) < '29991231'
                ) strt on strt.ProcessStatusId = ps.ProcessStatusID
    ) x
    left join (
        select 1 as Id, ps.Process as ProcessEvent
            , ps.ProcessStartDate 
            , ps.ProcessEndDate
            -- select strt.*
        from dbo.tbl_some_table ps 
        inner join (select max(ProcessStatusId) ProcessStatusId
                    from dbo.tbl_some_table 
                    where Process = 'YY Prcss Cmpltd' 
                    and convert(varchar(10), ProcessEndDate, 112) < '29991231'
                    ) enddt on enddt.ProcessStatusId = ps.ProcessStatusID
            ) y on y.Id = x.Id 
),

......기타 CT

중첩된 'With'는 지원되지 않지만 다음과 같이 두 번째 With를 항상 하위 쿼리로 사용할 수 있습니다.

WITH A AS (
                --WITH B AS ( SELECT COUNT(1) AS _CT FROM C ) SELECT CASE _CT WHEN 1 THEN 1 ELSE 0 END FROM B --doesn't work
                SELECT CASE WHEN count = 1 THEN 1 ELSE 0 END AS CT FROM (SELECT COUNT(1) AS count FROM dual)
                union all
                select 100 AS CT from dual
           )
              select CT FROM A

언급URL : https://stackoverflow.com/questions/1413516/can-you-create-nested-with-clauses-for-common-table-expressions

반응형