2012-04-03 88 views
0

我有以下列在SQL Server 2008中的表t_list
firstid, firstpoints, secondid, secondpoints如何執行這樣的查詢?

我想在一個SQL查詢,但以特定的方式,以選擇那些列。

我要選擇那些列的前400名,由firstpoints只爲firstid列排序,並secondpoints只爲一個查詢secondid列,例如:

SELECT TOP 400 firstid, firstpoints 
FROM t_list 
ORDER BY firstpoints desc 

select top 400 secondid, secondpoints 
FROM t_list 
ORDER BY secondpoints desc 

如何將上述兩個查詢合併爲一個查詢,返回輸出如

firstid, firstpoints, secondid, secondpoints 

1. firstidresult, firstpointresult, secondidresult, secondpointsresult 
2. etc... 

回答

4

這個工作的MS SQL Server

Select t1.FirstID, t1.FirstPoints, t2.SecondID, t2.SecondPoints 
From (Select Top 400 row_number() Over (Order By FirstPoints desc) As r, FirstID, FirstPoints From t_list) As t1 
    Join (Select Top 400 row_number() Over (Order By SecondPoints desc) As r, SecondID, SecondPoints From t_list) as t2 on t1.r = t2.r 

希望我理解正確你的問題上。

enter image description here

0
SELECT * 
FROM (
    SELECT TOP 400 FirstId 
     ,FirstPoints 
    FROM t_list 
    ORDER BY FirstPoints 
    ) f 

UNION 

SELECT * 
FROM (
    SELECT TOP 400 SecondId 
     ,SecondPoints 
    FROM t_list 
    ORDER BY SecondPoints 
    ) s 
0
WITH CTE1 AS 
(SELECT 1 as [Order], 
    firstid, 
    firstpoints, 
    Row_Number() OVER (ORDER BY firstpoints desc) as RowNum 
FROM t_list 
), 
CTE2 AS 
(SELECT 
    2, 
    secondid, 
    secondpoints, 
    Row_Number() OVER (ORDER BY secondpoints) as RowNum 
FROM t_list 
) 
SELECT [Order], 
    firstid as Id, 
    firstpoints as Points 
FROM CTE1 
WHERE RowNum <= 400 
UNION 
SELECT [Order], 
    secondid, 
    secondpoints 
FROM CTE2 
WHERE RowNum <= 400 
ORDER BY [Order], RowNum 
-1

你只需要你的兩個過濾器組合成使用 'UNION ALL'

一個表(SELECT TOP 400 firstid,firstpoints FROM t_list
ORDER BY firstpoints DESC)

UNION ALL

(select top 400 secondid,secondpoints
FROM t_list
ORDER BY secondpoints desc)