0

我之前问了一个问题,但我真的无法清楚地解释自己。

我制作了一张图表,希望能帮助解释我正在尝试做的事情。

在此处输入图像描述

我在同一个数据库中有两个单独的表。一张名为“Consumers”的表包含大约200 个字段,其中一个名为“METER_NUMBERS*”。然后是另一个名为“Customer_Info”的表,其中包含大约 30 个字段,其中一个名为“Meter”。这两个仪表字段是连接或任何方法所基于的。问题在于,并非两个表中的所有仪表编号都匹配,有些是 NULL 值,有些是两个表中的 0 值。

我想加入两个表之间具有匹配米数的记录的信息,但也将 NULL 和 0 值保留为它们自己的记录。两个表中都有 NULL 和 0 值,但我不希望它们连接在一起。

还有一些重复的字段名称,例如图中显示的位置。如果手动修复这些重复的字段名称更容易,我可以这样做,但能够以编程方式完成它会很酷。

关键是我需要一个新表中的结果!

这个过程将是一次性的,而不是我经常做的事情。

希望我清楚地解释了这一点,如果有人可以帮助我,那就太棒了!

如果需要更多信息,请告诉我。

谢谢。

4

4 回答 4

1

select * into New_Table From (select METER_NUMBER,Consumers.Location AS Location,Field4,Field5,Meter,Customer_Info.Location As Customer_Info_Location,Field2,Field3 From Consumers full external Join Customer_Info on Consumers.METER_NUMBER=Customer_Info.Meter And Consumers.Location=Customer_Info .Location) AS t

于 2013-08-13T11:59:25.717 回答
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
于 2013-08-13T01:08:59.170 回答
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
于 2013-08-13T01:12:58.900 回答
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);

我没有测试它,但你应该可以用它做点什么。

于 2013-08-13T01:22:37.517 回答