2013-10-10 64 views
1

我有一個名爲All_Sources與下列的表:琛TOP 5%,而所有的總和爲兩列

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 
+0

您能否提供一些示例數據來處理?我對一些事情很模糊。 – Khan

+0

請參閱上面的修改。這有幫助嗎? – slk

+0

是的,我認爲是。讓我知道我的答案是否能讓您獲得正確的結果。 – Khan

回答

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 
+0

感謝 - 作品像魅力。你能解釋一下'PARTITION BY(SELECT NULL)'部分嗎? – slk

+0

太棒了!你可以把它看作一個內聯的「GROUP BY」。由於我們不想對任何事物進行分組,所以我使用'SELECT NULL'作弊。請不要忘記提供幫助你的答案! :) – Khan

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