我之前问了一个问题,但我真的无法解释清楚。
我制作了一张图片,希望有助于解释我正在尝试做的事情。
我在同一个数据库中有两个单独的表。一个名为“消费者”的表格,其中包含 200个字段,其中一个名为“METER_NUMBERS *”。然后另一个名为“Customer_Info”的表包含大约30个字段,其中一个名为“Meter”。这两个仪表区域是连接或任何方法的基础。问题是,并非两个表中的所有仪表编号都匹配,有些是NULL值,有些是两个表中的值0。
我想加入两个表之间具有匹配的米数的记录的信息,但也保留NULL和0值作为它们自己的记录。两个表中都有NULL和0值,但我不希望它们连接在一起。
还有一些重复的字段名称,如图中所示的位置。如果手动修复这些重复的字段名称更容易,我可以这样做,但能够以编程方式执行它会很酷。
关键是我需要在新表格中获得结果!
这个过程将是一次性的事情,而不是我经常做的事情。
希望我能清楚地解释清楚,如果有人能帮助我,那就太棒了!
如果需要更多信息,请告知我们。
感谢。
答案 0 :(得分:1)
INSERT INTO new_table
SELECT * FROM
(SELECT a.*, b.* FROM Consumers a
INNER JOIN CustomerInfo b ON a.METER_NUMBER = b.METER and a.Location = b.Location
WHERE a.METER_NUMBER IS NOT NULL AND a.METER_NUMBER <> 0
UNION ALL
SELECT a.*, NULL as Meter, NULL as CustomerInfo_Location, NULL as Field2, NULL as Field3
FROM Consumers a
WHERE a.METER_NUMBER IS NULL OR a.METER_NUMBER = 0
UNION ALL
SELECT NULL as METER_NUMBER, NULL as Location, NULL as Field4, NULL as Field5, b.*
FROM CustomerInfo b
WHERE b.METER IS NULL OR b.METER = 0) c
答案 1 :(得分:1)
我想全外连接就是你需要的。
Create table #consumers (
meter_number int,
location varchar(50),
field4 varchar(50),
field5 varchar(50)
)
Create table #Customer_info (
meter int,
location varchar(50),
field1 varchar(50),
field2 varchar(50)
)
Insert into #consumers(meter_number ,location , field4 , field5 )
values (1234,'Dallas','a','1')
,(null, 'Denver','b','2')
,(5678,'Houston','c','3')
,(null,'Omaha','d','4')
,(0,'Portland','e','5')
,(2222,'Sacramento','f','6')
Insert into #Customer_info(meter , location )
values (1234,'Dallas')
,(null, 'Kansas')
,(5678,'Houston')
,(Null,'Denver')
,(0,'Boston')
,(4444,'NY')
Select c.*
,i.*
From #consumers c
full outer join #Customer_info i on c.meter_number=i.meter
and c.location=i.location
答案 2 :(得分:1)
我知道要从其他表创建一个新表,您可以使用以下片段:
CREATE TABLE New_table
AS (SELECT customers.Meter_number, customers_info.Meter_number, ...
FROM customers, customers_info
WHERE customers.Meter_number = customers_info.Meter_number
OR customers.Meter_number IS NULL OR customers_info.Meter_number = 0);
我没有测试它,但你应该能够做到这一点。
答案 3 :(得分:1)
选择*进入New_Table From(选择METER_NUMBER,Consumers.Location AS Location,Field4,Field5,Meter,Customer_Info.Location As Customer_Info_Location,Field2,Field3 From Consumers full outer Join Customer_Info on Consumers.METER_NUMBER = Customer_Info.Meter And Consumers。位置= Customer_Info.Location)AS t