2

我在Union all. 我知道我不能这样做。但是谁能帮帮我。

SELECT
ID, 
date1, 
date2 row_number() OVER (PARTITION BY ID ORDER BY date1 DESC )  as RN1, 
1 as Range
FROM 
(
SELECT ID,date1,
rn = row_number() OVER (PARTITION BY ID ORDER BY date1 )
FROM listing_History   (nolock)
WHERE [date1] <=   CONVERT(DATE,DATEADD(MONTH, -6, GETDATE()))  AND 
ID in (SELECT txt FROM [dbo].[fn_ListToTable](@listStr, ',')) 
)  AS A ORDER BY date1 DESC, date2 DESC

UNION ALL 

SELECT
ID, 
Date1, 
date2 row_number() OVER (PARTITION BY ID ORDER BY date1 DESC )  as RN1, 
1 as Range
FROM 
(
SELECT 
ID,
date1,
rn = row_number() OVER (PARTITION BY ID ORDER BY date1 )
FROM listing_History   (nolock)
WHERE [status_date] <=   CONVERT(DATE,DATEADD(MONTH, -3, GETDATE()) -1)
AND 
ID in (SELECT txt FROM [dbo].[fn_ListToTable](@listStr, ',')) 
) AS A ORDER BY date1 DESC,date2 desc
4

2 回答 2

1

应该总是有一个Order by最后一个选择UNIONUNION ALL

SELECT  
ID,
date1,
date2 row_number() OVER (PARTITION BY ID ORDER BY date1 DESC )  as RN1,
1 as Range
FROM 
(
SELECT ID,date1,
rn = row_number() OVER (PARTITION BY ID ORDER BY date1 )
FROM listing_History (nolock)
WHERE [date1] <= CONVERT(DATE,DATEADD(MONTH, -6, GETDATE())) 
AND 
ID in (SELECT txt FROM [dbo].[fn_ListToTable](@listStr, ',')) 
) AS A --ORDER BY date1 DESC, date2 DESC Remove order by from here

UNION ALL 

SELECT
ID, 
Date1, 
date2 row_number() OVER (PARTITION BY ID ORDER BY date1 DESC )  as RN1, 
1 as Range
FROM 
(
SELECT ID,date1,
rn = row_number() OVER (PARTITION BY ID ORDER BY date1 )
FROM listing_History with(nolock)
WHERE [status_date] <=   CONVERT(DATE,DATEADD(MONTH, -6, GETDATE()))
AND 
ID in (SELECT txt FROM [dbo].[fn_ListToTable](@listStr, ',')) 
)AS A
ORDER BY date1 DESC, date2 DESC
于 2013-05-08T21:48:54.470 回答
1

从除最后一个之外的所有 s 中删除所有ORDER BYsUNION并确保您在 中引用的列名ORDER BY与第一个相对应SELECT

于 2013-05-08T21:50:26.557 回答