2014-12-29 37 views
2

我想創建一個查詢,以顯示按字母順序與列名的第一個和最後5個事件有不同的標題的SQL Server,SQL查詢,不同headgs單查詢

EarliestEvent       EventDate 

£1 coin into circulation in Britain 1983-04-21 00:00:00.000 
3rd class travel abolished on BR 1956-06-03 00:00:00.000 
50p coin introduced in Britain  1969-10-14 00:00:00.000 
70mph speed limit on British roads 1965-12-22 00:00:00.000 
80th birthday of Queen Elizabeth II 2006-04-21 00:00:00.000 

LatestEvent          EventDate 

Yuri Gagarin first man in space     1961-04-12 00:00:00.000 
'Yorkshire Ripper' commits his first murder  1975-10-29 00:00:00.000 
York Minster struck by lightning     1984-07-09 00:00:00.000 
Yom Kippur War         1973-10-06 00:00:00.000 
Wreck of Titanic found       1985-09-01 00:00:00.000 

我與嘗試下面的查詢

Select a.* from (SELECT top 5 EventName AS 'EarliestEvent',EventDate FROM tblEvent order by EventName asc) as a 
union 
select b.* from (SELECT TOP 5 EventName As 'LatestEvent',EventDate FROM tblEvent order by EventName desc) as b; 

但我發現了有相同的列名頭結果

EarliestEvent        EventDate 

£1 coin into circulation in Britain   1983-04-21 00:00:00.000 
3rd class travel abolished on BR   1956-06-03 00:00:00.000 
50p coin introduced in Britain    1969-10-14 00:00:00.000 
70mph speed limit on British roads   1965-12-22 00:00:00.000 
80th birthday of Queen Elizabeth II   2006-04-21 00:00:00.000 
Wreck of Titanic found      1985-09-01 00:00:00.000 
Yom Kippur War        1973-10-06 00:00:00.000 
York Minster struck by lightning   1984-07-09 00:00:00.000 
'Yorkshire Ripper' commits his first murder 1975-10-29 00:00:00.000 
Yuri Gagarin first man in space    1961-04-12 00:00:00.000 

請建議我可能的方法.. 即時通訊學習關於sql server ..

在此先感謝所有。

回答

0

試試這個:

SELECT EventName, EventDate 
FROM (SELECT ROW_NUMBER() OVER (ORDER BY EventName ASC) RowNum, EventName, EventDate 
     FROM tblEvent 
     UNION 
     SELECT ROW_NUMBER() OVER (ORDER BY EventName DESC) RowNum, EventName, EventDate 
     FROM tblEvent 
    ) AS A 
WHERE RowNum <= 5 
ORDER BY EventName 
+0

這是行不通的。 'union'前面不能使用'order by' –

0

這是你想要的嗎?

SELECT a.EarliestEvent, a.EventDate, b.LatestEvent, b.EventDate 
FROM (SELECT ROW_NUMBER() OVER (ORDER BY EventName ASC) RowNum, EventName AS EarliestEvent, EventDate 
     FROM tblEvent) a 
     INNER JOIN 
     (SELECT ROW_NUMBER() OVER (ORDER BY EventName DESC) RowNum, EventName As LatestEvent, EventDate 
     FROM tblEvent) b 
    on a.RowNum =b.RowNum 
where a.RowNum<=5 and b.RowNum<=5 
ORDER BY a.RowNum