我持续需求的是将人员投入到“桶”中。基于某些性能指标。 NTILE并没有做我想做的事情,因为它将人口分成了相同的部门。从图形上看,你可以在这里看到我想要的东西:
这基本上是每个人的位置,以便管理层可以对它们进行分类。在这里你可以看到" top"数量的10%由12或13人提供(其中"累积"列达到10)。未图示的是"底部" 10%,人口超过200人。我目前正在使用Excel完成此任务,但我更愿意保持服务器端的复杂性。
以下是我如何达到百分比:
SELECT PREmain.*
, PREtotal.[Qty] [Total Qty]
, (PREmain.[Qty] / PREtotal.[Qty]) * 100 [Qty Percentage]
FROM PRE PREmain INNER JOIN
(SELECT [Week]
,[Year]
,SUM([Qty]) [Qty]
FROM PRE
GROUP BY [Week]
,[Year]) PREtotal ON PREmain.[Week] = PREtotal.[Week]
AND PREmain.[Year] = PREtotal.[Year]
......其中" PRE"由另一个查询填充。有人能告诉我如何才能做到这一点吗?
修改
我目前仍然坚持使用2008 R2,但以下答案将有望为2012年升级合理化提供催化剂。通过以下建议,我搜索了" SUM OVER SQL 2008"并发现了这个:
SQL Server 2008 using SUM() OVER(ORDER BY...)
这适用于2008年,并经过修改,为我工作。这是我的疑问:
,
PRE2 AS (
SELECT PREmain.*
, PREtotal.[Qty] [Total Qty]
, (PREmain.[Qty] / PREtotal.[Qty]) * 100 [Qty Percentage]
, PREtotal.[Gross Sales] [Total Gross Sales]
, (PREmain.[Gross Sales] / PREtotal.[Gross Sales]) * 100 [Gross Sales Percentage]
, PREtotal.[Net Sales] [Net Sales Qty]
, (PREmain.[Net Sales] / PREtotal.[Net Sales]) * 100 [Net Sales Percentage]
FROM PRE PREmain INNER JOIN
(SELECT [Week]
,[Year]
,SUM([Qty]) [Qty]
,SUM([Gross Sales]) [Gross Sales]
,SUM([Net Sales]) [Net Sales]
FROM PRE
GROUP BY [Week]
,[Year]) PREtotal ON PREmain.[Week] = PREtotal.[Week]
AND PREmain.[Year] = PREtotal.[Year])
SELECT a.*, x.s [Cumulative]
FROM PRE2 a
CROSS APPLY ( SELECT ISNULL(SUM(v), 0)
FROM ( SELECT b.[Qty Percentage]
FROM PRE2 b
WHERE b.[Qty Percentage] < a.[Qty Percentage]
AND a.[Week] = b.[Week]
) x(v)
) x(s)
ORDER BY a.[Qty Percentage]
花了3分钟才得到1719个结果。有点慢,但在我升级到2012之前,我一直在努力。
更新
使用TABLE变量可以更快。运行大约4秒钟。
答案 0 :(得分:1)
您应该能够使用分析所有前面行的分析函数来完成累积总计。我不确定哪些列包含在PREmain中,所以我在select语句中使用了*,它包含了原始查询。
SELECT
*,
SUM([Qty Percentage]) OVER (ORDER BY [Qty Percentage]) as Cumulative
FROM (SELECT PREmain.*
, PREtotal.[Qty] [Total Qty]
, (PREmain.[Qty] / PREtotal.[Qty]) * 100 [Qty Percentage]
FROM PRE PREmain INNER JOIN
(SELECT [Week]
,[Year]
,SUM([Qty]) [Qty]
FROM PRE
GROUP BY [Week]
,[Year]) PREtotal ON PREmain.[Week] = PREtotal.[Week]
AND PREmain.[Year] = PREtotal.[Year]
) a
答案 1 :(得分:1)
我只使用您提供的输出制作一个示例表,然后您可以将其扩展为您自己的查询
如果您使用的是SQL Server 2012+,则可以SUM()
使用OVER()
子句
CREATE语句
CREATE TABLE tbl(Id INT IDENTITY(1, 1), Staff INT, QtyPercentage DECIMAL(10, 9))
INSERT语句
INSERT INTO tbl VALUES (1855005, 0.968992248)
,(182806, 0.904392765)
,(429406, 0.839793282)
<强>查询强>
SELECT Staff
,QtyPercentage
,SUM(QtyPercentage) OVER(ORDER BY Id) AS Cumulative
FROM tbl
<强>输出强>
Staff QtyPercentage Cumulative
1855005 0.968992248 0.968992248
182806 0.904392765 1.873385013
429406 0.839793282 2.713178295