2016-07-20 153 views
0

我有一個表A,有4列: 名,發票,值,日期。將數據從表中複製到另一個表的過程

和表格B(FIRST_NAME,max_invoice_name,max_invoice_value,LAST_DATE)

我想爲了從移動數據,向B創建一個過程,但是:
FIRST_NAME應該在B中的一個時間,
max_invoice_name是最大發票值的名稱
max_invoice_value是最大值
last_date是來自同一first_name的發票的最近日期。

例如: 表A:

Smith | Invoice1 | 100 | 23.06.2016 
John | Invoice13 | 23 | 18.07.2016 
Smith | Invoice3 | 200 | 01.01.2015 


表B應該是:

Smith |Invoice3 | 200 | 23.06.2016 
John |Invoice13| 23 | 18.07.2016 
+0

其實我用一個臨時表,以保持所有不同的first_names,然後我逐行閱讀。如果存在於B =>用來自A的信息更新,如果不存在,則插入新行 – Johanna

回答

-1

試試這個

Insert into TableB(first_name, max_invoice_name, max_invoice_value, last_date) 
select t1.first_name,t1.invoice,t1,value,t2.date from TableA as t1 inner join 
(
select first_name, max(replace(invoice,'invoice','')) as invoice, max(date) as date 
    from TableA group by first_name 
) as t2 on t1.first_name=t2.first_name and t1.invoice=t2.invoice 
+0

首先,可能存在語法錯誤。其次,結果是錯誤的 - 考慮在2016/01/01有兩張相同的first_name的發票,Invoice2和2016/02/02的Invoice10 - 您在內部選擇中得到了什麼? – Arvo

0

您將需要創建2個標量函數getMaxNameForMaxValuegetLastDateByFirstName得到你想要的值。

INSERT INTO TableB (first_name, max_invoice_name, max_invoice_value, last_date) (SELECT DISTINCT first_name, getMaxNameForMaxValue(MAX(max_value)) AS 'max_invoice_name', MAX(max_invoice_value) AS 'max_invoice_value', getLastDateByFirstName(first_name) AS 'lastDate' FROM Table A) 
1

像這樣的東西應該工作:

select *, (select max(date) from #Table1 T1 where T1.first_name = X.first_name) 
from (
    select 
    *, 
    row_number() over (partition by first_name order by invoice_Value desc) as RN 
    from 
    #Table1 
) X 
where RN = 1 

行號採取與最大的價值選擇行的關懷,和最大GET的日期。你需要列出正確的位置列,而不是*

0

您可以使用這樣的事情:

--INSERT INTO TableB 
SELECT first_name, 
     invoice_name, 
     invoice_value, 
     last_date 
FROM (
    SELECT a.first_name, 
      a.invoice_name, 
      a.invoice_value, 
      COALESCE(p.last_date,a.last_date) as last_date, 
      ROW_NUMBER() OVER (PARTITION BY a.first_name ORDER BY a.last_date) as rn 
    FROM TableA a 
    OUTER APPLY (SELECT TOP 1 * FROM TableA WHERE first_name = a.first_name and last_date > a.last_date) as p 
) as res 
WHERE rn = 1 

由於輸出:

first_name invoice_name invoice_value last_date 
John  Invoice13  23    2016-07-18 
Smith  Invoice3  200    2016-06-23 
相關問題