我有这样的桌子
+------------+------------+----------+
| Name | Class | Launched |
+------------+------------+----------+
| California | California | 1921 |
+------------+------------+----------+
| Haruna | California | 1916 |
+------------+------------+----------+
| Test | California | NULL |
+------------+------------+----------+
我需要用单元格中的值替换NULL值:
我使用函数执行此操作,但我认为这不是最佳解决方案。
CREATE FUNCTION fn_mainprod (@classname varchar(50))
RETURNS int
AS
BEGIN
RETURN
(
SELECT launched from Ships
WHERE name = class AND class = @classname
);
END
GO
SELECT name, class,
CASE
WHEN launched IS NULL THEN fn_mainprod(class)
ELSE launched
END as Prod
FROM Ships
输出:
+------------+------------+----------+
| Name | Class | Prod |
+------------+------------+----------+
| California | California | 1921 |
+------------+------------+----------+
| Haruna | California | 1916 |
+------------+------------+----------+
| Test | California | 1921 |
+------------+------------+----------+
请您推荐不使用功能的方法。
答案 0 :(得分:1)
您可以使用outer apply
:
select s.name, s.class, coalesce(s.Launched, s2.Launched) as Prod
from Ships s outer apply
(select top (1) s1.Launched
from Ships s1
where s1.class = s.class and s1.name = s.class and
s.Launched is null
order by ?
) s2;