如何在sql中找出重复记录并对列进行计算?

时间:2013-05-09 08:58:25

标签: sql sql-server sql-server-2008 tsql group-by

我有一个表有这样的数据:

CUSIP   Quantity  Date           Price
AF0      500000   5/16/2013      1
AE4      400000   5/6/2013      1.0825
AE4      500      5/6/2013      1

我需要检查列CUSIPDate如果我在同一天有重复的CUSIP,那么我需要进行以下计算。

  1. 为两者添加数量而不是显示重复记录只需要显示一条记录(数量总和)。

  2. 重新计算价格如下: NewPrice =((400000 * 1.0825)+(500 * 1.00))/(400000 + 500)= 1.08148

  3. 例如,在使用上述数据时需要显示类似

    的输出
    CUSIP   Quantity  Date          Price
    AF0     500000    5/6/2013      1
    AE4     400500    5/6/2013      1.082397004
    

    我当前的SQL查询是

    Select AVG(Price),CUSIP,Quantity,DATE,Price 
    from DailyData where a.Date = '25-12-2011'
    GROUP BY CUSIP,DATE
    

    Plase帮我纠正我的SQL查询

1 个答案:

答案 0 :(得分:3)

Select
     CUSIP,
     DATE,
     SUM(Quantity) AS SumQty,
     SUM(Quantity*Price)/SUM(Quantity) AS NewPrice
from
   DailyData a
where
   a.Date = '25-12-2011'
GROUP BY
   CUSIP,DATE

示例:

DECLARE @t TABLE (CUSIP varchar(50), Quantity int, SomeDate date, Price decimal(19,9));
INSERT @t VALUES
 ('AF0', 500000, '20130516', 1),('AE4', 400000, '20130506',1.0825),('AE4', 500, '20130506', 1)

Select
     CUSIP,
     SomeDate,
     SUM(Quantity) AS SumQty,
     SUM(Quantity*Price)/SUM(Quantity) AS NewPrice
from
   @t a
GROUP BY
   CUSIP,SomeDate