rN rD rnc d expectedResult
abc1m 2010-03-31 abc 5.7 5.7 + 1.7 +9.6
abc3m 2010-03-31 abc 5.7 5.7 + 1.7 +9.6
abc1y 2010-03-31 abc 5.7 5.7 + 1.7 +9.6
xfx1m 2010-03-31 xfx 1.7 5.7 + 1.7 +9.6
xfx3m 2010-03-31 xfx 1.7 5.7 + 1.7 +9.6
xfx1y 2010-03-31 xfx 1.7 5.7 + 1.7 +9.6
tnt1m 2010-03-31 tnt 9.6 5.7 + 1.7 +9.6
tnt3m 2010-03-31 tnt 9.6 5.7 + 1.7 +9.6
tnt1y 2010-03-31 tnt 9.6 5.7 + 1.7 +9.6
------------------------------------
abc1m 2010-04-01 abc 2.2 2.2 + 8.9 + 5.5
abc3m 2010-04-01 abc 2.2 2.2 + 8.9 + 5.5
abc1y 2010-04-01 abc 2.2 2.2 + 8.9 + 5.5
xfx1m 2010-04-01 xfx 8.9 2.2 + 8.9 + 5.5
xfx3m 2010-04-01 xfx 8.9 2.2 + 8.9 + 5.5
xfx1y 2010-04-01 xfx 8.9 2.2 + 8.9 + 5.5
tnt1m 2010-04-01 tnt 5.5 2.2 + 8.9 + 5.5
tnt3m 2010-04-01 tnt 5.5 2.2 + 8.9 + 5.5
tnt1y 2010-04-01 tnt 5.5 2.2 + 8.9 + 5.5
预期结果是特定日期的不同rnc的总和 如何实现这一目标。 我想使用类似下面的代码,但不起作用。
select *,
sum (d) over (partition by rD, distinct rnc) as expectedResult
from myTable
where ...--some condition
order by ...--order by some columns
使用SQL Server 2012,谢谢
编辑:关于暂停的问题,这是怎么回事。如果一个人只看expectedResult
栏,那么它是不是很清楚?我应该添加什么才能让它变得更好?
- 每个人都有d。假设每个集合都是示例中给出的形式。 (回答一条评论)
答案 0 :(得分:1)
这里我们使用cte对相同的行进行分组。 这样,我们可以只选择select中每个组的第一行。
;WITH cte
AS
(
SELECT *,
GroupRowIndex = ROW_NUMBER() OVER (PARTITION BY rateDate, rnc, d ORDER BY (SELECT 1))
FROM myTable
)
SELECT *,
expectedResult = SUM(d) OVER (PARTITION BY rateDate)
FROM cte
WHERE GroupRowIndex = 1
AND ...--some condition
ORDER BY ...--order by some columns
答案 1 :(得分:1)
由于第一列的最后2个字符是可重复的,并且您实际上是在分区中进行求和,请试一试并告诉我这是否是您要求的
create table #TempTable (rn nvarchar(10), rD date, rnc nvarchar(10), d decimal(5,2))
insert into #TempTable (rn, rD, rnc, d)
values
('abc1m','2010-03-31','abc', 5.7),
('abc3m','2010-03-31','abc', 5.7),
('abc1y','2010-03-31','abc', 5.7),
('xfx1m','2010-03-31','xfx', 1.7),
('xfx3m','2010-03-31','xfx', 1.7),
('xfx1y','2010-03-31','xfx', 1.7),
('tnt1m','2010-03-31','tnt', 9.6),
('tnt3m','2010-03-31','tnt', 9.6),
('tnt1y','2010-03-31','tnt', 9.6),
------------------------------------
('abc1m','2010-04-01','abc', 2.2),
('abc3m','2010-04-01','abc', 2.2),
('abc1y','2010-04-01','abc', 2.2),
('xfx1m','2010-04-01','xfx', 8.9),
('xfx3m','2010-04-01','xfx', 8.9),
('xfx1y','2010-04-01','xfx', 8.9),
('tnt1m','2010-04-01','tnt', 5.5),
('tnt3m','2010-04-01','tnt', 5.5),
('tnt1y','2010-04-01','tnt', 5.5)
select rn, rD, rnc, d, SUM(d) over (partition by right(rn,2), rD) as 'Sum'
from #TempTable
order by Rd
答案 2 :(得分:1)
您可以使用交叉申请来应用基于rD的不同rnc值的总和
SELECT t1.*, ca.expectedResult
FROM myTable t1
CROSS APPLY (
SELECT SUM(d) expectedResult
FROM (SELECT DISTINCT rnc, d
FROM myTable t2
WHERE t2.rd = t1.rd) AS s) ca
答案 3 :(得分:0)
如果你不想表现,很容易
select rN, rD, rnc, d, sub.dsum as expectedResult
from yourtable
join (
select rD, rnd, sum(d) as dsum
from (select distinct rD, rnd, d
from yourtable
) x
group by rD, rnd
) sub on yourtable.rD = sub.rD and yourtable.rnd = sub.rnd