我在Netezza中设置了两个交易表,如下所示。当连接ID和transactionCount上的表,并尝试返回Answer时,行9998,9996,9995等将有空值。如何使用填充了最后结果的Answer列返回所有transactionCount值?
所以例如9998将返回U,9996将返回Y,9988将返回N,依此类推。
ID transactionCount ID transactionCount Answer
1 9999 1 9999 U
1 9998 1
1 9997 1 9997 Y
1 9996 1
2 9999 2 9999 Y
2 9998 2
2 9997 2
2 9996 2 9996 N
2 9995 2
3 9999 3 9999 Y
3 9998 3
3 9997 3 9997 N
3 9996 3
3 9995 3
感谢您的帮助。
答案 0 :(得分:0)
您没有指定RDBMS,所以我只使用MySQL。
select transactionCount1,
(select answer
from t2
where transactionCount2 >= t1.transactionCount1
order by transactionCount2
limit 1) as answer
from t1
order by 1 desc
这是一个显示它工作的小提琴:http://sqlfiddle.com/#!2/dde35e/3
<强> EDIT ... 强>
在回答问题的更改时,查询变为:
select id1, transactionCount1,
(select answer
from t2
where id2 = id1 and transactionCount2 >= t1.transactionCount1
order by transactionCount2
limit 1) as answer
from t1
order by 1 asc, 2 desc
而sql小提琴现在是:http://sqlfiddle.com/#!2/36aacc/1