连接两个表并在同一条语句中连接相同的列名

时间:2019-06-21 16:05:02

标签: sql sql-server

我有一个很大的原始数据表。它很长,我正在尝试对它进行转置。我正在从中加入两个选择语句。这样,我得到了多个具有相同名称的列。这是一个完整的外部联接,我希望两个单独的列具有与一个列相同的名称。由于它是一个外部联接,因此我不想只选择一个表列,就像选择t1.c1

谢谢!

SELECT *
  FROM (SELECT * FROM [LabData].[dbo].[FermHourlyDCSData] where Attribute='Urea') P
  full outer JOIN 
(SELECT * FROM [LabData].[dbo].[FermHourlyDCSData] where Attribute='Water to Mash Total Water') FPD ON 
P.[TimeStamp] = FPD.[TimeStamp] 
and P.Site = FPD.Site
and P.Element = FPD.Element

实际:

Site Attribute Timestamp Value Site Attribute Timestamp Value
AD   Urea      1/1/2019  127   Null Null      Null      Null
Null Null      Null      Null  AD   Water     1/1/2019  7.5

期望/期望:

Site Attribute Timestamp Value Value
AD   Urea      1/1/2019  127  Null
AD   Water     1/1/2019  Null 7.5

3 个答案:

答案 0 :(得分:1)

ISNULL是您应该为此使用的

ISNULL(p.Site,fpd.Site) as [Site]

答案 1 :(得分:1)

尝试一下,它不是很漂亮,但是确实可以工作:

SELECT 
[Site] = ISNULL(P.[Site], FPD.[Site]),  
[Attribute] = ISNULL(P.[Attribute], FPD.[Attribute]),   
[Timestamp] =   ISNULL(P.[Timestamp], FPD.[Timestamp]), 
[Value] =   ISNULL(P.[Value], FPD.[Value]), 
[Element] =ISNULL(P.[Element], FPD.[Element])
FROM (SELECT * FROM [dbo].[FermHourlyDCSData] where Attribute='Urea') P
full outer JOIN 
(SELECT * FROM [dbo].[FermHourlyDCSData] where Attribute='Water to Mash Total Water') FPD ON 
P.[TimeStamp] = FPD.[TimeStamp] 
and P.Site = FPD.Site
and P.Element = FPD.Element

答案 2 :(得分:0)

也许我遗漏了一些东西,但是您似乎想要一个更简单的查询:

select Site, Attribute, Timestamp,
       (case when Attribute = 'Urea' then Value end) as value_u,
       (case when Attribute = 'Water to Mash Total Water' then Value end) as value_2
from [LabData].[dbo].[FermHourlyDCSData]
where Attribute  in ('Urea', 'Water to Mash Total Water')