我有一些查询返回ID列表及其特定列的SUM。
select TICKETID,SUM(IMPACT) AS S
from incident
GROUP BY TICKETID
ORDER BY S
结果就像这样:
TICKETID S
INC491943 10
INC491944 20
INC491945 30
INC491946 40
INC491950 50
因此,这个结果有5行,我需要从行中获得所有行的80%的结果值。
因此,这将是具有值40的行,因为它具有5行,并且5的80%是数字4(在这种情况下为第四行)。 所以最终结果只是值40。
当然,如果80%的行结果是例如4.2,那么我们检索第4行 如果结果是4.7,那么我们检索第5行。
这有可能吗?解决方案是什么? 感谢
答案 0 :(得分:1)
嗯。我倾向于这样做:
SELECT i.*
FROM (SELECT TICKETID, SUM(IMPACT) AS S,
SUM(SUM(IMPACT)) OVER () as total_s,
SUM(SUM(IMPACT)) OVER (ORDER BY SUM(IMPACT)) as cumulative_s
FROM incident
GROUP BY TICKETID
) i
WHERE cumulative_s >= 0.8 * total_s AND
(cumulative_s - s) < 0.8 * total_s;
以上是&#34; s&#34;的计算。如果你只想要它的行:
SELECT i.*
FROM (SELECT TICKETID, SUM(IMPACT) AS S,
COUNT(*) OVER () as cnt,
ROW_NUMBER() OVER (ORDER BY SUM(IMPACT)) as seqnum
FROM incident
GROUP BY TICKETID
) i
WHERE seqnum >= 0.8 * cnt AND
(seqnum - 1) < 0.8 * cnt;