SQL查询:从2个表中乘法

时间:2015-02-24 19:39:12

标签: sql sql-server

假设SQL Server数据库中有2个表:

table1,价格变化时存储产品价格:

|Date      |Product|Price|
--------------------------
|2014-01-01|     A |   2$|
|2015-01-01|     A |   3$|

table2,按日期存储已售商品的数量:

|Date       | Product | Quantities|
-----------------------------------
|2014-01-01 |     A   |    200    |
|2014-06-01 |     A   |    300    |
|2015-02-01 |     A   |    100    |

我的问题:如何通过编写SQL查询按产品的日期计算销售额(价格x数量):

|Date       | Product | Sales   |
---------------------------------
|2014-01-01 | A       |     400 |
|2014-06-01 | A       |     600 |
|2015-02-01 | A       |     300 |

2 个答案:

答案 0 :(得分:1)

我假设你想在拍卖会之前或之前拿到最近的价格。在设计此类数据结构时,通常最好在每条记录上都有一个有效的结束日期,而不仅仅是生效日期。唉,这不是你所拥有的。

您可以使用相关子查询或apply来获取价格。下面是一个使用列和表名称的示例(假设price实际上存储的数字不是字符串):

select t2.*, (t2.quantity * p.price) as sales
from table2 t2 outer apply
     (select top 1 t1.price
      from table1 t1
      where t1.product = t2.product and t1.date <= t2.date
      order by t1.date desc
     ) p

答案 1 :(得分:0)

select [date], product, price*quantities 
from 
(
    select 
    t2.*, t1.price ,
    ROW_NUMBER() over (partition by t2.[date], t2.product order by t1.[date] desc) as num
    from table1 t1
    join table2 t2 on  t1.[date] <= t2.[date]
) T
where T.num = 1