2015-02-24 66 views
0

假设有2个表中的SQL Server数据库:SQL查询:乘法从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查询来计算销售(股价×数量)的日期产品:

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

你尝试过什么,到底是什么?这并不困难,并且涉及SQL中最基本的操作符之一。 – 2015-02-24 19:53:35

回答

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 
+0

应该是't2.quantity * p.price'而不是't2.quantity * t1.price' – ASh 2015-02-24 20:00:49

+0

也应该使用'order by t1.Date desc'在子选择中,因为子选择将返回随机价格否则! – ASh 2015-02-24 20:04:33

+0

戈登,可以更详细地说明在这种情况下应该使用什么样的结构?有一个专栏“结束日期”有什么好处(如何使查询数据更容易)? – deadcode 2015-02-24 22:10:05

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 
+0

嗨,我试过了你的查询。不幸的是它会返回所有日期的最新价格。 – deadcode 2015-02-24 22:02:17

+0

其实它的作品!我只是改变了“<=" to "> =”和哈利路亚:)。你能告诉更多关于查询吗?我不明白是什么,例如。分区,行号()等。 – deadcode 2015-02-24 22:17:34

+0

@deadcode,row_number()是sql-server中的排名函数之一。 '由t2分割'[日期],t2.product'将结果集划分成产品组,在某个日期销售;之后'row_number()'根据排序设置每个组中的每一行的顺序位置('t1 by [。date] desc')。然后,应用过滤器'在哪里T.num = 1'我采取每个日期出售的每一个产品的最新价格。另请参阅https://msdn.microsoft.com/en-us/library/ms186734.aspx – ASh 2015-02-25 07:55:38