1

我有一个用以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
4

2 回答 2

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
于 2013-10-10T18:33:20.537 回答
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
于 2013-10-10T18:22:40.743 回答