2

我有一个下表:

贸易ID | 股票代码 | 日期 | 数量

此表包含我进行的所有交易。我想知道我上周赚了多少,以及我在每只股票上的总金额。

股票代码 | 数量_in_lst_week | 剩余金额

例如:

1 | A | 2013-01-01 | 200 
2 | A | 2013-06-25 |-100 
3 | B | 2013-06-25 | 100 
4 | C | 2013-04-01 | 100 

今天是我们当地时间 2013 年 6 月 26 日,所以我应该得到:

A |-100 | 100
B | 100 | 100
C | 0   | 100 

我认为这不是一件难事,但我写了一个复杂的子查询,如下所示:

SELECT lst_week.stock_code, 
       lst_week.amount_in_lst_week, 
       total.amount_remaining 
  FROM (SELECT t1.stock_code, 
               SUM(COALESCE(t2.amount, t2.amount, 0)) AS amount_in_lst_week 
          FROM trade t1
     LEFT JOIN trade t2 ON t1.trade_id = t2.trade_id 
                       AND TO_DAYS(NOW()) - TO_DAYS(t1.date) <= 7
      GROUP BY t1.stock_code) lst_week,
       (SELECT stock_code, SUM(amount) AS amount_remaining 
          FROM trade
      GROUP BY stock_code) total 
 WHERE lst_week.stock_code = total.stock_code;

它有效,但我想知道是否可以在没有子查询的情况下做到这一点?还是有更简单的方法?谢谢。

4

3 回答 3

1

大多数数据库都支持窗口函数。你可以得到你想要的:

select stock_code,
       sum(case when date >= CURRENT_TIMESTAMP - 7 then amount_remaining else 0
           end) as amount_in_lst_week, 
       sum(sum(amount_remaining)) over ()
from trade
group by stock_code, amount_in_lst_week ;

确切的日期/时间函数取决于数据库。例如,在 SQL Server 中,您将使用:

when date >= cast(CURRENT_TIMESTAMP - 7 as date)

在甲骨文中:

when date >= trunc(sysdate - 7)

MySQL 不支持窗口函数,因此您必须使用连接或相关子查询:

select stock_code,
       sum(camount_remaining) as amount_in_lst_week, 
       (select sum(amount_remaining) from trade t)
from trade t
where date >= now() - interval 7 days 
group by stock_code, amount_in_lst_week ;
于 2013-06-26T02:39:00.503 回答
1

这个怎么样:

select 
     Stock_code
    ,[1st week] = sum(case when [date] >= getDate()-7 then amount else 0 end)
    ,remainder = sum(amount)
from data
group by Stock_code
于 2013-06-26T02:54:06.487 回答
0

你可以试试这个:

SELECT t.stock_code, 
       Coalesce(t2.amount, 0) AS `amount_in_lst_week`, 
       Sum(t.amount)          AS `amount_remaining` 
FROM   trade t 
       LEFT JOIN (SELECT stock_code, 
                         sum(amount) as `amount` 
                  FROM   trade 
                  WHERE  date BETWEEN Date_add(CURRENT_DATE(), INTERVAL -7 day) 
                                      AND 
                                      CURRENT_DATE() GROUP BY stock_code) t2 
              ON t2.stock_code = t.stock_code 
GROUP  BY t.stock_code; 

虽然这仍然有子查询......

SQLFiddle 示例

于 2013-06-26T03:25:07.373 回答