我有一個表,我想選擇頂部5行由列A頂部。我也想有一個第6行標題爲「其他」,它將值除了前5行以外的所有列。SQL Server 2005 - 選擇頂部N加「其他」
有沒有簡單的方法來做到這一點?我開始有:
select top 5
columnB, columnA
from
someTable t
order by
columnA desc
我有一個表,我想選擇頂部5行由列A頂部。我也想有一個第6行標題爲「其他」,它將值除了前5行以外的所有列。SQL Server 2005 - 選擇頂部N加「其他」
有沒有簡單的方法來做到這一點?我開始有:
select top 5
columnB, columnA
from
someTable t
order by
columnA desc
沒有測試,但嘗試這樣的事:
select * from (
select top 5
columnB, columnA
from
someTable t
order by
columnA desc
union all
select
null, sum(columnA)
from
someTable t
where primaryKey not in (
select top 5
primaryKey
from
someTable t
order by
columnA desc
)
) a
這是從我的頭頂,我會garuntee可怕高效:
SELECT TOP 5 columnB, columnA
FROM comTable t
ORDER BY columnA desc
UNION
SELECT 'Other', (A.Sum - B.Sum) AS Summary
FROM (SELECT SUM(columnA) FROM someTable) A
JOIN (SELECT SUM(One) FROM
(SELECT TOP 5 columnA FROM someTable ORDER BY columnA DESC)) B
我最近很多地方使用了EXCEPT statemnet:(未測試,但我給它去了)
select top 5
columnB, columnA
from
someTable t
order by
columnA desc
UNION ALL
SELECT 'OTHER' ColumnB, SUM(ColumnA)
FROM
(SELECT ColumnB, ColumnA
FROM someTable t
EXCEPT
select top 5
columnB, columnA
from
someTable t
order by
columnA desc
) others
select top 5 columnB, columnA
from someTable
order by columnA desc
select SUM(columnA) as Total
from someTable
在客戶端做減法。
100%未經測試,並且不在我的頭頂,但您可以提供類似這樣的東西。如果我有機會測試今晚我會更新帖子,但有一瓶酒晚餐,這是星期五晚上... :)
WITH CTE AS
(
SELECT
ColumnB,
ColumnA,
ROW_NUMBER() OVER (ORDER BY ColumnB) AS RowNumber
FROM
dbo.SomeTable
)
SELECT
CASE WHEN RowNumber <= 5 THEN ColumnB ELSE 'Other' END AS ColumnB,
SUM(ColumnA) AS ColumnA
FROM
CTE
GROUP BY
CASE WHEN RowNumber <= 5 THEN ColumnB ELSE 'Other' END
ORDER BY
MIN(RowNumber)
編輯:看起來這幾個工作後,愚蠢的語法錯誤。我已經糾正了這些問題,所以應該按照上面列出的那樣工作。儘管我不能在大型數據集上表現,但值得一試。
注:我明確沒有總結columnB,因爲你沒有要求。 – RedFilter 2008-12-12 22:07:18