我一直在努力工作几个小时,看起来非常简单的查询让我(非常)疯狂。 我有2张桌子:
产品
Code Var
AAI85CLASS2000 9005N
AAI85CLASS2000 9005P
时报
Code Var Time
AAI85CLASS2000 NULL 8,68
AAI85CLASS2000 CROM 9,68
AAI85CLASS2000 9005N 19,68
结果我想得到
Code Var Time
AAI85CLASS2000 9005N 19,68
AAI85CLASS2000 9005P 8,68
当存在匹配的Var时,应考虑具体的时间。当没有匹配的Var时,应考虑通用时间(其中Var为NULL)。 我请求帮助。感谢。
答案 0 :(得分:0)
试试这个:
Select i.code, i.var, case when max(t.var) is not null then max(case when t.var is not null then t.time end) else max(t.time) end time
From items i left join times t
On i.code = t.code and (i.var = t.var or t.var is null)
Group by i.code, i.var;
答案 1 :(得分:0)
以下是使用Outer Join
SELECT a.Code,
a.Var,
COALESCE(b.time, c.time)
FROM Items a
LEFT JOIN Times b
ON a.Code = b.Code
AND a.Var = b.Var
LEFT JOIN Times c
ON ( a.Code = b.Code
AND a.Var = c.Var
AND b.Var IS NULL ) -- To find the non matching var's in previous join
OR c.Var IS NULL -- To find the time from var which is NULL
答案 2 :(得分:0)
这是一种方法:
SELECT I.Code,
I.Var,
ISNULL(T.Time, (SELECT Time FROM Times WHERE Var IS NULL AND Code = I.Code)) Time
FROM Items I
LEFT JOIN Times T ON I.Code = T.Code AND I.Var = T.Var