找到并替换特定值的T-SQL

时间:2018-07-17 10:50:24

标签: sql sql-server tsql

我有这样的桌子

+------------+------------+----------+
| Name       | Class      | Launched |
+------------+------------+----------+
| California | California | 1921     |
+------------+------------+----------+
| Haruna     | California | 1916     |
+------------+------------+----------+
| Test       | California | NULL     |
+------------+------------+----------+

我需要用单元格中的值替换NULL值:

  • 名称和类的值相同;
  • NULL行中的Class值等于Class和Name相同的行中的Class值。

我使用函数执行此操作,但我认为这不是最佳解决方案。

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     |
+------------+------------+----------+

请您推荐不使用功能的方法。

1 个答案:

答案 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;