SQL Server 2005 - 选择前N加“其他”

时间:2008-12-12 21:59:26

标签: sql sql-server

我有一个表,我想在其中选择一行A列的5行。我还希望有一个标题为“其他”的第6行,它除了前5行之外的所有值的A列值。< / p>

有一种简单的方法吗?我开始时:

select top 5 
    columnB, columnA 
from 
    someTable t
order by
    columnA desc

5 个答案:

答案 0 :(得分:3)

未经测试,但尝试这样的事情:

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

答案 1 :(得分:1)

select top 5 columnB, columnA
from someTable 
order by columnA desc

select SUM(columnA) as Total
from someTable

在客户端进行减法。

答案 2 :(得分:1)

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)

编辑:看起来这在一些愚蠢的语法错误之后起作用了。我已经纠正了这些,所以它应该如上所述。我不能谈论大型数据集的性能,但是值得一试。

答案 3 :(得分:0)

这是我的头脑,我将保证非常高效:

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

答案 4 :(得分:0)

我最近使用了EXCEPT语句:(未经测试,但我试一试)

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