C4n 2022-04-16 15:17 采纳率: 80%
浏览 162
已结题

如何SQL 语句UNION实现当一个表中的一列内容为空时则取另一个表的另一列

问题遇到的现象和发生背景

img

img

img

问题相关代码,请勿粘贴截图

以下代码为SQL server 中生成数据表内容的代码,供测试使用
create table customer
(
custid int primary key,
cfirstname char(30),
csurname char(30),
billingaddress char(30),
cgender char(1) check(cgender in('M','F'))
);
create table shoporder
(
ordid int primary key,
deliveryaddress char(30),
spid int,
custid int,
foreign key(spid) references salesperson(spid),
foreign key(custid) references customer(custid)
);
use "3120004023";
INSERT
INTO customer(custid,cfirstname,csurname,cgender,billingaddress)
VALUES
('1','Casey','Cartwright','F','1 Roma Ave Cranbourne'),
('2','Evan','Chambers','M','8 David St Dandenong'),
('3','Calvin','Owens','M','7 Long Rd Lara'),
('4','Frannie','Morgan','F','9 Down Pde Upwey'),
('5','Cappie','Jones','M','6 Mist St Toorak'),
('6','Dana','Stockwell','F','2 Tree St Epping'),
('7','Ash','Howard','F','4 Elm Ave Elwood');
use "3120004023";

INSERT
INTO shoporder(ordid, deliveryaddress,spid,custid)
VALUES
(41,NULL,23,1),
(51,NULL,23,1),
(42,NULL,21,2),
(43,NULL,23,2),
(49,NULL,24,2),
(44,'1 John St Hawthorn',26,3),
(48,NULL,26,3),
(45,'1254 Dunstall Rd Coorparoo',22,4),
(47,'727 Hudson Rd Glenorchy',26,4),
(50,'517 Franklin St Dowerin',22,4),
(46,NULL,21,6);

我的解答思路和尝试过的方法

尝试过使用case when 达到相同的效果,但题目要求是使用 union子句
select ordid,case when deliveryaddress is NULL then billingaddress else deliveryaddress end as address from shoporder,customer where shoporder.custid=customer.custid;

我想要达到的结果

img

  • 写回答

1条回答 默认 最新

  • 数仓白菜白 2022-04-16 17:08
    关注

    union怎么写呀
    我看到这个题,第一想到的就是case when。然后看到你下面也说了你用case when 。
    本来以为我能解答,结果我也不会用union🙃

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 4月19日
  • 已采纳回答 4月16日
  • 创建了问题 4月16日

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图