自我加入+左加入Sql Server

时间:2017-06-27 08:47:04

标签: sql-server-2008 join

我有一个表可以存储不同的测量值,类型作为关联列来存储测量类型。

以下是带有数据的样本表

enter image description here

我可以自己加入表格,根据日期获得ht和wt值。我的要求是,我还需要所有日期的wt值,即使表中没有该日期的ht。

示例结果

enter image description here

编辑:我尝试了以下查询,但它只返回第一行。

SELECT 
  ta.uid, ta.value as 'wt', lta.value as 'ht', ta.date,ta.id as lftid, lta.id as rtid FROM 
  [test].[dbo].[tbl2] ta
     LEFT JOIN [test].[dbo].[tbl2] Lta 
        ON ta.[date] = Lta.[date]
       AND ta.[uid] = 11 WHERE 
      ta.type = 'wt'
  AND Lta.type ='ht'

2 个答案:

答案 0 :(得分:0)

您在where子句中引用正确的别名这一事实有效地将您的left join更改为inner joinRead this answer to find out why.
为避免这种情况,请将where子句中的条件移至on子句:

SELECT ta.uid, 
       ta.value as 'wt', 
       lta.value as 'ht', 
       ta.date,
       ta.id as lftid, 
       lta.id as rtid 
FROM [test].[dbo].[tbl2] ta
LEFT JOIN [test].[dbo].[tbl2] Lta 
ON ta.[date] = Lta.[date]
AND ta.type = 'wt'
AND Lta.type ='ht'           
WHERE ta.[uid] = 11 

答案 1 :(得分:0)

只需对您的查询进行一些更改即可:

SELECT 
  ta.uid, ta.value as 'wt', lta.value as 'ht', ta.date,ta.id as lftid, lta.id as rtid FROM 
  [test].[dbo].[tbl2] ta
     LEFT JOIN [test].[dbo].[tbl2] Lta 
        ON ta.[date] = Lta.[date]
       AND ta.[uid] = 11  and ta.type<>Lta.type
       WHERE 
      ta.type = 'wt'
  AND isnull(Lta.type,'ht') ='ht'