[英]Copy specific table data from one database to another in SQL Server
[英]SQL Server: inserting data from one database to another database structure by specific date
我需要一些幫助,以將數據從一個數據庫拉到具有不同模式的另一個數據庫中。我正在編寫一個PHP腳本來實現這一點。
我的第一個查詢是:
SELECT orderid, customerid, validation_date, test_type, test_result, amount
WHERE test_type IN ('ph', 'bh')
我得到如下結果
1 101001 10-01-2018 bh 5 20.00
2 101001 10-01-2018 ph 3 25.00
3 101002 11-02-2018 bh 4 20.00
4 101002 11-02-2018 ph 2 25.00
5 101003 15-02-2018 bh 3 20.00
6 101003 15-02-2018 ph 4 25.00
7 101001 25-04-2018 bh 4 20.00
8 101001 25-04-2018 ph 2 25.00
我想在每個特定日期的一行中將此數據插入到結構的另一個SQL Server表中。
另一個數據庫的表模式如下:
itemid, customerid, validation_date, ph_value, bh_value
所以我希望結果進入數據庫,如下所示:
1 101001 10-01-2018 3 5
2 101002 11-02-2018 2 4
3 101003 15-02-2018 2 3
4 101001 25-04-2018 2 4
請問您如何使用SQL查詢實現此建議? 我做了一個選擇,現在想以上述格式插入數據庫
您可以將數據“按原樣”上傳到SQL Server,然后使用SQL引擎根據需要對其進行按摩 。
如果我們考慮兩個值(ph,bh)可能不同時出現的情況,那么您將需要FULL OUTER JOIN
。 您將需要創建一個新表和一個序列來產生插入,如:
create table my_table (
id int,
customer_id int,
validation_date date,
ph_value real,
bh_value real
);
create sequence seq1; -- a sequence is needed to generate IDs.
然后,可能產生您的數據的查詢如下所示:
insert into my_table (id, customer_id, validation_date, ph_value, bh_value)
select
next value for seq1,
coalesce(ph.customer_id, bh.customer_id),
coalesce(ph.validation_date, bh.validation_date),
ph.amount,
bh.amount
from (select * from t where test_type = 'ph') ph
full outer join (select * from t where test_type = 'bh') bh
on ph.customer_id = bh.customer_id
and ph.validation_date = bh.validation_date
您可以使用聚合來透視數據:
select customer_id, validation_date,
max(case when test_type = 'ph' then ph.test_result end) as ph_value,
max(case when test_type = 'bh' then ph.test_result end) as bh_value
from t
group by customer_id, validation_date;
目前尚不清楚itemid
來自何處。 如果即時計算,我建議在目標表中使用一個identity
列。
然后,您可以使用SELECT . . . INTO
SELECT . . . INTO
SELECT . . . INTO
或INSERT
將數據放在另一個表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.