简体   繁体   中英

SQL Server: inserting data from one database to another database structure by specific date

I need some help to pull data from one database into another database with a different schema I am writing a PHP script to achieve this.

My first query is:

SELECT orderid, customerid, validation_date, test_type, test_result, amount 
WHERE test_type IN ('ph', 'bh')

and I get the result as following

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

I want to insert this data into another SQL Server table of the structure in one line for each specific date.

The table schema of the other database is as follows:

itemid, customerid, validation_date, ph_value, bh_value 

So I want the result to go into the database as follows:

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 

Please can you advice on how I can achieve this using a SQL query? I did a select, AND NOW want to insert into the database in the above format

You can upload your data to SQL Server "as is" and then use the SQL engine to massage it as you want.

If we considering the case when both values (ph, bh) may not be present simultaneously, then you would need a FULL OUTER JOIN . You would need to create a new table and a sequence to produce the inserts, as in:

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.

Then the query that could produce your data can look like:

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

You can use aggregation to pivot the data:

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;

It is unclear where itemid comes from. If calculated on the fly, I would suggest an identity column in the target table.

Then you can use either SELECT . . . INTO SELECT . . . INTO SELECT . . . INTO or INSERT to put the data in another table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM