2015-04-07 56 views
0

我有一個表tblOriginal它看起來像這樣(和無主鍵):如何插入aonther SQL Server表

employeeId code amount date 
----------------------------- 
emp01  sbk 10000 201501 
emp02  sbk 10002 201501 
emp02  cka 2000 201501 
emp03  sbk 10003 201501 
emp04  sbk 10004 201501 
emp01  sbk 20000 201502 
emp01  dgr 5000 201502 
emp02  sbk 20002 201501 
emp02  qaw 2000 201502 
emp02  dng 4000 201502 
emp03  sbk 20003 201502 
emp04  sbk 20004 201502 

我需要做的獲得與代碼SBK所有數據到表什麼命名tblEmpemployeeId是主鍵),如下所示:

employeeId code amount date amount2 date2 
---------------------------------------------- 
emp01  sbk 10000 201501 20000 201502 
emp02  sbk 10002 201501 20002 201501 
emp03  sbk 10003 201501 20003 201502 
emp04  sbk 10004 201501 20004 201502 

然後拿到剩餘的數據到名爲tblOthers看如下另一個表。主鍵也是employeeId

employeeId code amount date code2 amount2 date2 
-------------------------------------------------- 
emp02  cka 2000 201501 
emp01  dgr 5000 201502 
emp02  qaw 2000 201502 dng 4000 201502 

我的問題是我不知道如何利用它具有相同的名稱爲employeeId到表中的數據和存儲數據到列

任何幫助將是欣賞。

所有的表已經創建

+0

INSERT INTO T1選擇... ...從...在那裏我 – jarlh

+0

想到這絕對量2,但我的問題是關於'tblOriginal'有數據具有相同的** employeeId **,但日期不同但'tblEmp'和'tblOthers' ** employeeId **是我的'PRIMARY KEY',所以不應該有相同的數據* * employeeId ** – Esther

+0

您的tblOthers表存在一些問題。如果EmployeeId是主鍵,則它不能包含具有相同employeeId emp02的2行。 –

回答

-1

請參考以下鏈接:

http://www.w3schools.com/sql/sql_and_or.asp

SQL和&或運營商正在使用基於篩選記錄不止一個條件。

操作實例 -

SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; 

OR操作實例 -

SELECT * FROM Customers WHERE City='Berlin' OR City='München'; 

合併AND &或 -

SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München'); 
0

,如果有,可以用一些這樣的事對其他表

;with temp as (
select empemployeeId, 
lag(amount,1,null) over (partition by empemployeeId ORDER BY date ASC) as amount, 
lag(date,1,null) over (partition by empemployeeId ORDER BY date ASC) as date, 
lag(amount,1,null) over (partition by empemployeeId ORDER BY date DESC) as amount2, 
lag(date,1,null) over (partition by empemployeeId ORDER BY date DESC) as date2, 
from tblOriginal 
) 
select empemployeeId,'sdk',amount,date,amount2,date2 into tblEmp from temp to 
where to.code='sdk'