TOP 5 PERCENT的总和以及所有两列的总和

时间:2013-10-10 18:15:33

标签: sql sql-server

我有一个名为All_Sources的表,其中包含以下列:

svcmonth
source
member
cost

我正在尝试编写一个查询,该查询将返回TOP 5 PERCENT成员作为第一列的成本总和,并将表中所有成员的成本总和作为第二列。我可以通过以下两个查询单独获取这两个数字:

SELECT SUM(t1.fivepercentcost)
FROM
(SELECT
TOP 5 PERCENT member, 
SUM(cost) AS fivepercentcost
FROM dbo.All_Sources
WHERE svcmonth = '2013, 01' AND source = 'HC'
GROUP BY member
ORDER BY SUM(cost) DESC) t1

SELECT SUM(cost) AS 
FROM dbo.All_Sources
WHERE svcmonth = '2013, 01' AND source = 'HC'

但是,我遇到的问题是尝试将这两个查询放在一起,这样两个结果就会在两列中并排显示。我一直试图与CTE和OVER()功能合作,没有任何运气。非常感谢任何帮助。

编辑:示例数据

svcmonth   source   member   cost
2012, 12   HC       1        50
2012, 12   BA       1        40
2013, 01   HC       1        55
2013, 01   HC       2        100
2013, 01   BA       1        50
2013, 02   BA       2        45

2 个答案:

答案 0 :(得分:1)

这应该会让你到那里。诀窍是执行OVERPARTITION BY (SELECT NULL),以便您可以在表格的内联SUM中执行此操作。

SELECT  SUM(fivepercentcost) AS fivepercentcost, 
        Total
FROM (
    SELECT TOP 5 PERCENT 
            member,
            SUM(cost) AS fivepercentcost,
            Total
    FROM (
        SELECT  member,
                cost, 
                SUM(cost) OVER(PARTITION BY (SELECT NULL)) AS Total     
        FROM    dbo.All_Sources
        WHERE   svcmonth = '2013, 01' 
            AND source = 'HC'
    ) A
    GROUP BY member, Total
    ORDER BY SUM(cost) DESC
) A
GROUP BY Total

答案 1 :(得分:0)

声明两个变量,单独加载它们并按如下方式选择它们:

DECLARE @TOP5 AS FLOAT
DECLARE @ALL AS FLOAT

SELECT @TOP5 = SUM(t1.fivepercentcost)
FROM
(SELECT
TOP 5 PERCENT member, 
SUM(cost) AS fivepercentcost
FROM dbo.All_Sources
WHERE svcmonth = '2013, 01' AND source = 'HC'
GROUP BY member
ORDER BY SUM(cost) DESC) t1

SELECT @ALL = SUM(cost) AS 
FROM dbo.All_Sources
WHERE svcmonth = '2013, 01' AND source = 'HC'

SELECT @TOP5, @ALL