我有一个表可以存储不同的测量值,类型作为关联列来存储测量类型。
以下是带有数据的样本表
我可以自己加入表格,根据日期获得ht和wt值。我的要求是,我还需要所有日期的wt值,即使表中没有该日期的ht。
示例结果
编辑:我尝试了以下查询,但它只返回第一行。
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'
答案 0 :(得分:0)
您在where
子句中引用正确的别名这一事实有效地将您的left join
更改为inner join
。
Read 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'