请考虑一个包含两列的供应商表:VendorName
和PayableAmount
我正在寻找一个查询,该查询返回按PayableAmount
降序排列的前十名供应商和其他应付金额的总和为"其他"在第11行。
显然,sum of PayableAmount
表中的Vendors
应该等于sum of PayableAmount
中的Query
。
答案 0 :(得分:1)
从技术上讲,可以在一个查询中执行此操作:
declare @t table (
Name varchar(50) primary key,
Amount money not null
);
-- Dummy data
insert into @t (Name, Amount)
select top (20) sq.*
from (
select name, max(number) as [Amount]
from master.dbo.spt_values
where number between 100 and 100000
and name is not null
group by name
) sq
order by newid();
-- The table itself, for verification
select * from @t order by Amount desc;
-- Actual query
select top (11)
case when sq.RN > 10 then '<All others>' else sq.Name end as [VendorName],
case
when sq.RN > 10 then sum(sq.Amount) over(partition by case when sq.rn > 10 then 1 else 0 end)
else sq.Amount
end as [Value]
from (
select t.Name, t.Amount, row_number() over(order by t.Amount desc) as [RN]
from @t t
) sq
order by sq.RN;
它甚至适用于从2005年开始的任何SQL Server版本。但是,在现实生活中,我更愿意分别计算这两个部分,然后UNION
。
答案 1 :(得分:0)
这将执行您正在寻找的查询。首先提取前10名中的那些,然后UNION
将结果与排名较高的供应商进行比较,但调用'Other'
WITH rank AS (SELECT
VendorName,
PayableAmount,
ROW_NUMBER() OVER (ORDER BY PayableAmount DESC) AS rn
FROM vendors)
SELECT VendorName,
rn,
PayableAmount
FROM
rank WHERE rn <= 10
UNION
SELECT VendorName, 11 AS rn, PayableAmount
FROM
(
SELECT 'Other' AS VendorName,
SUM(PayableAmount) AS PayableAmount
FROM
rank WHERE rn > 10
) X11
ORDER BY rn
这已在SQLFiddle中测试过。
答案 2 :(得分:0)
这是第11行
我没看过它
declare @i int
set @i=
(select sum(x.PayableAmount)
from
(select * from table
except
select top 10 *from table
order by PayableAmount desc) as x)
select 'another',@i