比较同一表中的记录并计算不同日期的差异

时间:2015-05-11 08:05:04

标签: sql sql-server sql-server-2012

我有一张表,其中包含某些日期的股票及其权重列表。我想做的是在两个不同的日期选择属于投资组合的股票并比较权重。下面的简单例子,

Date 1st March 2015              Date 1st May 2015
Stock Name    Weight             Stock Name    Weight
ABC           20                 MNO           30
DEF           15                 XYZ           25
MNO           40                 LMN           30
LMN           25                 PPP           10
                                 KLM           5
                                 ABC           20

结果我想要

 Stock Name    Weight Change
 ABC           0
 DEF           -15
 MNO           -10
 LMN           5
 PPP           10
 KLM           5
 XYZ           25

到目前为止,这就是我所需要的一切!

 with t0 as
(select * from PORT_WGT
and port_name = 'My Port'
and wgt <> 0 
and pricedate = '2015-01-02'),
t1 as
(select * from PORT_WGT
where counterparty = 'JPM'
and port_name = 'My Port'
and wgt <> 0 
and pricedate = '2015-01-30')
select * from t0 union all
select * from t1

更新

刚刚意识到我使用了错误的联接类型,请查看我的更新查询。我只需要计算权重的变化

 with t0 as
 (select * from PORT_WGT
 where port_name = 'My Port'
 and wgt <> 0 
 and pricedate = '2015-01-02'),
 t1 as
(select * from PORT_WGT
where port_name = 'My Port'
and wgt <> 0 
and pricedate = '2015-01-30')
select coalesce(t0.sedol, t1.sedol), coalesce(t0.co_name, t1.co_name)  from      t0 full outer join t1 on t0.sedolchk  = t1.sedolchk 

1 个答案:

答案 0 :(得分:5)

我认为你需要在两个CTE之间FULL OUTER JOIN

;WITH t0 AS (
   SELECT * 
   FROM PORT_WGT
   WHERE counterparty = 'JPM'
         and port_name = 'My Port'
         and wgt <> 0 
         and pricedate = '2015-01-02'
), t1 as (
   SELECT * 
   FROM PORT_WGT
   WHERE counterparty = 'JPM'
         and port_name = 'My Port'
         and wgt <> 0 
         and pricedate = '2015-01-30')
SELECT COALESCE(t0.[Stock Name], t1.[Stock Name]) AS [Stock Name],
       COALESCE(t1.Weight, 0) - COALESCE(t0.Weight, 0) AS WeightChange
FROM t0 
FULL OUTER JOIN t1 ON t0.[Stock Name] = t1.[Stock Name]
ORDER BY [Stock Name]

SQL Fiddle Demo

您也可以使用条件聚合

select [Stock Name], 
       SUM(CASE WHEN pricedate = '2015-01-30' THEN Weight 
                ELSE 0
           END)
       -
       SUM(CASE WHEN pricedate = '2015-01-02' THEN Weight 
                ELSE 0
           END) AS WeightChange
from PORT_WGT
where counterparty = 'JPM' and port_name = 'My Port' and wgt <> 0 
      and (pricedate = '2015-01-02' OR pricedate = '2015-01-30')
group by [Stock Name]

SQL Fiddle Demo