SQL:选择列(如果其中没有数据)

时间:2018-10-10 06:11:24

标签: sql

我在DB2中有两个表:customerorder。它们中存在的数据是:

客户:

customer_id first_name  last_name   city            state    zipcode
1           George      Washington  Mount Vernon    VA       22121
2           John        Adams       Quincy          MA       02169
3           Thomas      Jefferson   Charlottesville VA       22902
4           James       Madison     Orange          VA       22960
5           James       Monroe      Charlottesville VA       22902

顺序:

order_id    order_date  amount   customer_id
1           NA          NA          1
2           03/14/1760  $78.50      3
3           NA          NA          2
4           09/03/1790  $65.50      3
5           07/21/1795  $25.50      10
6           11/27/1787  $14.40      9

使用以下查询联接表:

select first_name, last_name, order_date, amount
from customers c
inner join orders o
on c.customer_id = o.customer_id

这给了我

first_name  last_name   order_date  order_amount
George      Washington  NA          NA
John        Adams       NA          NA
Thomas      Jefferson   03/14/1760  $78.50
Thomas      Jefferson   09/03/1790  $65.50

我只想为那些有数据的记录获取记录。

预期的O / P:

first_name  last_name   order_date  order_amount
Thomas      Jefferson   03/14/1760  $78.50
Thomas      Jefferson   09/03/1790  $65.50

如何使用SQL达到以上结果?任何帮助都会非常有帮助。

2 个答案:

答案 0 :(得分:2)

这里的示例代码基本上忽略了空值,或者您的情况是订单金额和订单日期列均为'NA'

select first_name, 
last_name, 
order_date, 
amount
from customers c
inner join orders o on c.customer_id = o.customer_id
WHERE (o.order_date <> 'NA' OR o.order_date IS NOT NULL) 
AND (o.order_amount <> 'NA' OR o.order_amount IS NOT NULL)

答案 1 :(得分:1)

使用此代码:

select first_name, last_name, order_date, amount
from customers c
inner join orders o
on c.customer_id = o.customer_id
WHERE o.order_date IS NOT NULL AND o.order_amount IS NOT NULL