繁体   English   中英

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 . . . INTOINSERT将数据放在另一个表中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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