CREATE TABLE #TEMP(
ROW INT IDENTITY,
LOT CHAR(1),
GU CHAR(1),
GROUPCODE INT)
INSERT INTO #TEMP
VALUES
('A', '1', 1),
('B', '1', 2),
('A', '2', 3),
('B', '2', 4),
('A', '1', 3),
('B', '1', 4),
('A', '2', 5),
('B', '2', 5),
('C', '1', 5)
;
WITH QTY(LOT, GROUPCODE, GU, LEVEL, row, prn_code) AS
(
SELECT LOT, GROUPCODE, GU, 1 AS LEVEL, CAST(row AS INT) ROW, 0 as prn_code
FROM #temp
WHERE LOT = 'C'
and gu = (SELECT MAX(Gu)
FROM #temp
WHERE LOT = 'C')
UNION ALL
SELECT A.LOT, A.GROUPCODE, A.GU, B.LEVEL + 1, CAST(A.ROW AS INT), B.row
FROM #temp A
INNER JOIN QTY B
ON (B.GU = 1 AND A.GU = 2 AND A.GROUPCODE = B.GROUPCODE)
OR (B.GU = 2 AND A.GU = 1 AND A.LOT = B.LOT AND A.GROUPCODE <> B.GROUPCODE AND A.GROUPCODE = (SELECT MAX(GROUPCODE)
FROM #TEMP
WHERE GU = A.GU
AND LOT = B.LOT))
)
SELECT * FROM QTY
DROP TABLE #TEMP
여기서 재귀 아래에 MAX부분땜에
재귀 공통 테이블 식 'QTY'의 재귀 부분에는 GROUP BY, HAVING 또는 집계 함수를 사용할 수 없습니다.
이런 에러가 발생하는데 저런 모양의 재귀쿼리를 동작이 되도록 다른쿼리로 바꿀수 있나요?