我的数据如下所示:
name SAL1 SAL2 SAL3
A 10 20 30
B 11 21 31
C 12 22 32
D 13 23 33
我试图获得一个额外的计算列,即 10/25 * 100
[A / Sum的SAL1(Sal1 DESC的TOP 2 Sal1订单)]
而不是考虑分母中所有记录的总和,我需要考虑sal desc的前2个sal命令
分别用于其余行。 随后与其他专栏一起使用。
name SAL_calculated
A 40
B 44
C 48
D 52
按Asc命名为name列,Desc为其余列命令
答案 0 :(得分:5)
SELECT name, SAL_calculated = SAL * 100.0 / SUM(SAL) OVER ()
FROM table
ORDER BY name ASC, SAL_calculated DESC
表示SAL1的A / Sum(TOP 2 Sal1 ORDER BY Sal1 DESC)
select *, t.SAL1 * 100.0 / c.TOP2_SAL
from tbl t
CROSS APPLY
(
SELECT TOP2_SAL = SUM(SAL1)
FROM
(
SELECT TOP 2 SAL1
FROM tbl
ORDER BY SAL1 desc
) c
) c
答案 1 :(得分:0)
试试这个:
SELECT name, SAL1, SAL2, SAL3,
ROUND(SAL1 * 1.0 / x.v * 100, 1) AS SAL_calculated
FROM mytable
CROSS JOIN (SELECT SUM(SAL1) FROM mytable) AS x(v)
ORDER BY name, SAL1 DESC, SAL2 DESC, SAL3 DESC
答案 2 :(得分:0)
这就是我所做的,
在子查询中,我们可以将前n个或整个记录集的聚合存储到变量 a 中,然后将该变量用作分母。
声明@a为整数= 0 SELECT @a = ( SELECT TOP2_SAL = SUM(SAL1) 从 ( 选择TOP 2 SAL1 来自[dbo]。[TESTY] 订购SAL1 desc ) C ) 选择 * t.SAL1 * 100 / @a 来自[dbo]。[TESTY] t