我有這樣的table資料:
Fund | EffectiveDate | SomeOtherColumns | COST
F123 | 2022-04-25 | something | 345
F123 | 2022-04-24 | fdsdfdff | 340
F123 | 2022-04-20 | hi | 360
F123 | 2022-04-17 | hello | 810
F456 | 2022-04-28 | some other fund | 110
F456 | 2022-04-26 | some other fund | 220
F456 | 2022-04-25 | some other fund | 460
F456 | 2022-04-15 | some other fund | 215
示例定義如下:
CREATE TABLE [dbo].[MyTable](
[Fund] [NCHAR](10) NOT NULL,
[EffectiveDate] [DATE] NOT NULL,
[SomeOtherColumns] [NVARCHAR](50) NULL,
[Cost] [INT] NOT NULL
) ON [PRIMARY]
GO
對于我的結果查詢中的每個基金(在本例中為 F123 和 F456),我希望每個基金每天只有一行。我想取每只基金中最新的前三名,將其與當天的價值結合起來。因此,例如結果將是:EffectiveDateCOST
Fund | EffectiveDate | SomeOtherColumns | COST | COST DAY BEFORE | COST DAY BEFORE THAT |
F123 | 2022-04-25 | something | 345 | 340 | 360 |
F456 | 2022-04-28 | some other fund | 110 | 220 | 460 |
我知道我應該使用 aPIVOT但我什至不知道如何解決它。
我的查詢甚至沒有編譯!
SELECT * FROM (
SELECT TOP(3)
FUND, EffectiveDate, Cost
FROM MyTable
ORDER BY EffectiveDate DESC
) Results
PIVOT (
SUM(Cost)
FOR EffectiveDate
IN (
FUND, EffectiveDate, Cost
)
) AS PivotTable
uj5u.com熱心網友回復:
我不認為這是一個關鍵的情況,而是一個排名的情況。
您希望每只基金只有一行,包含最高日期的成本,以及之前的最后兩個,對嗎?
如果是這樣,您可以使用 CTE 對基金的資料磁區進行排名,并為成本生成額外的列,然后對其進行過濾以僅將第一個值帶入排名。
像這樣:
CREATE TABLE [dbo].[MyTable](
[Fund] [NCHAR](10) NOT NULL,
[EffectiveDate] [DATE] NOT NULL,
[SomeOtherColumns] [NVARCHAR](50) NULL,
[Cost] [INT] NOT NULL
) ON [PRIMARY]
insert into MyTable(Fund , EffectiveDate , SomeOtherColumns , COST) values
('F123' , '2022-04-25' , 'something' , 345),
('F123' , '2022-04-24' , 'fdsdfdff' , 340),
('F123' , '2022-04-20' , 'hi' , 360),
('F123' , '2022-04-17' , 'hello' , 810),
('F456' , '2022-04-28' , 'some other fund' , 110),
('F456' , '2022-04-26' , 'some other fund' , 220),
('F456' , '2022-04-25' , 'some other fund' , 460),
('F456' , '2022-04-15' , 'some other fund' , 215)
;with rankingCte as (
select *,
LAG(Cost) over(order by EffectiveDate ASC) [COST DAY BEFORE],
LAG(Cost,2) over(order by EffectiveDate ASC) [COST DAY BEFORE THAT],
rank() over(partition by Fund order by EffectiveDate desc) as dateRanking
from MyTable
)
select Fund, EffectiveDate, SomeOtherColumns, Cost, [COST DAY BEFORE],
[COST DAY BEFORE THAT]
from rankingCte
where dateRanking=1
| 基金 | 生效日期 | 其他一些列 | 成本 | 費用前一天 | 前一天的費用 |
|---|---|---|---|---|---|
| F123 | 2022-04-25 | 某物 | 345 | 340 | 360 |
| F456 | 2022-04-28 | 其他一些基金 | 110 | 220 | 460 |
你可以看到它在這個DB Fiddle上作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/492730.html
上一篇:在SQLServer中使用Merge時用Update子句替換多個“匹配時”
下一篇:創建可自行重置的列
