我想为没有一个的CUST_ID记录(表A)选择一个可用的PROMO_CODE(表B)。 我想我有每个表的基本SQL,但不确定如何将它们组合在一起作为输出。
-----表A -----
CUST_ID|CREATED_DATE|MY_CODE
XYZ111|1/1/2015|5
XYZ222|1/1/2015|6
XYZ333|7/12/2018|
XYZ444|7/13/2018|
XYZ555|7/14/2018|
XYZ666|2/2/2012|3
XYZ777|2/2/2012|2
XYZ888|7/15/2018|
XYZ999|6/6/2016|4
XYZ1110|6/6/2016|1
-----表B -----
PROMO_CODE|PROMO_CODE_STATUS
1|assigned
2|used
3|
4|used
5|assigned
6|
7|
8|assigned
9|assigned
10|
----所需的输出-----
CUST_ID|MY_NEW_CODE
XYZ333|3
XYZ444|6
XYZ555|7
XYZ888|10
----到目前为止,我还没有连接-----
Select a.CUST_ID, b.PROMO_CODE as MY_NEW_CODE
(Select a.CUST_ID, a.CREATED_DATE, a.MY_CODE
from $A$ a where
a.MY_CODE is NULL AND trunc(a.CREATED_DATE) >= trunc(sysdate -1))
(Select b.PROMO_CODE, b.PROMO_CODE_STATUS
from $B$ b where
b.PROMO_CODE_STATUS is NULL)
答案 0 :(得分:0)
我会这样想:
Select a.CUST_ID, b.PROMO_CODE as MY_NEW_CODE
FROM $A$ a, $B$ b
WHERE a.MY_CODE = b.PROMO_CODE
AND trunc(a.CREATED_DATE) >= trunc(sysdate -1)
AND b.PROMO_CODE_STATUS is NULL
答案 1 :(得分:0)
我最终在每个表上使用ROW_NUMBER(),并且有效:
选择*从 (SELECT ROW_NUMBER()OVER(按a.CUST_ID ASC排序)AS Row_CUST_ID,a.CUST_ID,a.MY_NEW_CODE FROM $ A $ a其中a.MY_NEW_CODE为NULL并且trunc(a.LOADED_DATE)> = trunc(sysdate -1))c 内部联接 (SELECT ROW_NUMBER()OVER(ORDER BY b.PROMO_CODE ASC)AS Row_PROMO_CODE,b.PROMO_CODE,b.PROMO_CODE_STATUS FROM $ B $ b其中b.PROMO_CODE_STATUS为NULL)p 开启c.Row_CUST_ID = p.Row_PROMO_CODE
它产生预期的结果:
ROW_CUST_ID | CUST_ID | MY_NEW_CODE | ROW_PROMO_CODE | PROMO_CODE | PROMO_CODE_STATUS
1 | 111 | | 1 | BBB |
2 | 222 | | 2 | DDD |
3 | 333 | | 3 | FFF |
从更新的表格中:
-----表A
CUST_ID | MY_NEW_CODE | LOADED_DATE
111 | | 2018-07-18 00:00:00.0
222 | | 2018-07-18 00:00:00.0
333 | | 2018-07-19 00:00:00.0
444 | | 2018-07-12 00:00:00.0
-----表B
PROMO_CODE | PROMO_CODE_STATUS
AAA |二手
BBB |
CCC |已分配
DDD |
EEE |已分配
FFF |