使用'ORDER BY'对查询执行'UNION'

时间:2013-05-08 21:46:49

标签: sql-server

我在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

2 个答案:

答案 0 :(得分:1)

最后选择Order byUNION

时,应始终有一个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 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

答案 1 :(得分:1)

从最后一个ORDER BY中移除所有UNION,并确保您在ORDER BY中引用的列名与第一个SELECT对应。