2015-02-24 64 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