我在聚合/汇总查询(子查询?(的输出时遇到问题。这是我的初始代码和输出:
代码:
SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
SELECT
AsOfDate,
round(ColA/sum(ColB) * (ColC),4) As 'Monthly_Return'
from xyz.abc
WHERE
AsOfDate BETWEEN '2021-05-25' AND '2021-05-26'
and ColD like '123%'
GROUP BY AsOfDate, ColA,ColB,ColC
| AsOfDate |MarketV(ColA)|MarketV(ColB)|Return(ColC)|(ColD)|
|------------|-------------|-------------|------------|------|
| 2021-05-25 | 8891171.14| 8891171.14| -0.81166911| 123|
| 2021-05-25 | 14219713.92| 14219713.92| 2.12135625| 123|
| 2021-05-25 | 3102248.42| 3102248.42| 0.36907554| 123|
| 2021-05-26 | 8819004.25| 8819004.25| 0.88822511| 123|
| 2021-05-26 | 14521364.71| 14521364.71| 1.84104756| 123|
| 2021-05-26 | 3113698.06| 3113698.06| 0.44211577| 123|
|The sum of ColB for 2021-05-25 is 26,213,133.48|
|The sum of ColB for 2021-05-25 is 26,454,067.02|
我想要按日期分组的ColAi/ColB*ColCi的总和。
|For 2021-05-25 | Return |
|--------------------------------------------|---------|
|8891171.14 / 26,213,133.48 * -0.81166911 =|-0.275308|
|14219713.92 / 26,213,133.48 * 2.12135625 =|1.150762 |
|3102248.42 / 26,213,133.48 * 0.36907554 =|0.043679 |
|For 2021-05-26 | Return |
|--------------------------------------------|---------|
|8819004.25 / 26,454,067.02 * 0.88822511 =|0.296108 |
|14521364.71 / 26,454,067.02 * 1.84104756 =|1.0106016|
|3113698.06 / 26,454,067.02 * 0.44211577 =|0.0520379|
我当前的代码显示以下输出:
AsOfDate | Monthly_Return |
---|---|
2021-05-25 | -0.275308 |
2021-05-25 | 1.100762 |
2021-05-25 | 0.043679 |
2021-05-26 | 0.296108 |
2021-05-26 | 1.0106016 |
2021-05-26 | 0.0520379 |
如果查询真的给了你想要的子结果,那么你所要做的就是把查询放在子查询中,然后再次聚合:
SELECT
asofdate,
SUM(monthly_return)
FROM ( <your query here> ) subquery
GROUP BY asofdate
ORDER BY asofdate;
由于您很少按照所选的所有列进行分组,我将向您展示一些样本数据和结果,因此您可以仔细检查:
有了这个数据
AsOfDate | 第A列 | 第B列 | 第C列>第D列|
---|---|---|---|
2021-05-25 | 12 | 32 | 123 |
2021-05-25 | 12 | 32 | |
2021-05-25 | 12 | 32 | |
2021-05-25 | 12 | <1>3123 | //tr>|
2021-05-25 | 12 | <1>3123 | //tr>|
2021-05-25 | 12 | <1>3123 | //tr>
用您的新需求和新列名完全重写。(因为你已经选择了一个答案,所以它的价值是多少。(
with a as (
select AsOfDate
, ColA
, sum(ColB) over (partition by AsOfDate) as ColB
, ColC
from abc
where AsOfDate BETWEEN '2021-05-25' AND '2021-05-26'
and ColD like '123%'
)
select AsOfDate
, cast(round(sum(ColA * ColC / ColB), 4) as decimal(6,4)) as 'Monthly_Return'
from a
group by AsOfDate
;
也许下次,在你的问题中加入一个dbfiddle,这样你的结构和数据就可用了。此外,当你第一次问这个问题时,要包括你想要的结果。