繁体   English   中英

在SQL中替换子查询结果

[英]Replace sub-query result in SQL

我需要如果子查询结果为null,则它将替换为“-”。 我试过了

REPLACE ( string_expression , string_pattern , string_replacement )

REPLACE((SELECT [StandNo] FROM [dbo].[BusStand] where id=b.[ReturnStand]), char(0), '-')

但是没有解决方案,因为我认为它将子查询作为string_expression。

下面的解决方案(SELECT isnull([StandNo],'-') FROM [dbo].[BusStand] where id=b.[ReturnStand])也不起作用。

抱歉,我发现问题与子查询b.[ReturnStand]无关b.[ReturnStand]为空,因为它选择了零行并将空值放在结果中。 我的查询是这样的。

SELECT b.[Id],
       b.[Date],
       (SELECT [BusId]
        FROM   [dbo].[Bus]
        WHERE  id = [breakDownBusNo])           AS Bus,
       (SELECT [RouteNo]
        FROM   [dbo].[Route]
        WHERE  id = bl.[routeNo])               AS [Route No],
       (SELECT [StandName]
        FROM   [dbo].[BusStand]
        WHERE  id = b.[stand])                  AS [Breakdown Stand],
       b.[DeadKm]                               AS [Distance From Depo],
       (SELECT COALESCE([StandNo], 0)
        FROM   [dbo].[BusStand]
        WHERE  id = b.[ReturnStand])            [On Route Stand],
       COALESCE([ReturnKm], 0)                  AS [Distance of on route place],
       ( b.[DeadKm] + COALESCE([ReturnKm], 0) ) AS Total
FROM   [dbo].[BreakDown] AS b
       INNER JOIN [dbo].[Bus Log] AS bl
               ON b.BusLogId = bl.Id
       INNER JOIN [dbo].[DriverAttendance] AS da
               ON da.Id = b.DrvrAttnDnceIdLog 

请不要查询复杂性,我只需要显示我在哪里使用它。 现在我该如何在路线支架上用'-'代替null。

您的语法错误您需要在string_expression添加列名或变量

SELECT REPLACE(isnull([StandNo],0),'0', '-') FROM [dbo].[BusStand] 
where id=b.[ReturnStand]

或更好的方法

无需使用Replace

....IN
( SELECT isnull([StandNo],'-') FROM [dbo].[BusStand] 
where id=b.[ReturnStand] )

请试试:

(SELECT ISNULL([StandNo] ,  '-') FROM [dbo].[BusStand] where id=b.[ReturnStand])

使用COALESCE功能

SELECT COALESCE((SELECT [StandNo] FROM [dbo].[BusStand] where id=b.[ReturnStand]) , '-')
FROM [dbo].[tableA] AS b;

你可以直接做到这一点

SELECT b.[Id],
       b.[Date],
       (SELECT [BusId]
        FROM   [dbo].[Bus]
        WHERE  id = [breakDownBusNo])           AS Bus,
       (SELECT [RouteNo]
        FROM   [dbo].[Route]
        WHERE  id = bl.[routeNo])               AS [Route No],
       (SELECT [StandName]
        FROM   [dbo].[BusStand]
        WHERE  id = b.[stand])                  AS [Breakdown Stand],
       b.[DeadKm]                               AS [Distance From Depo],

   **** (SELECT isnull([StandNo], '-')
    FROM   [dbo].[BusStand]
    WHERE  id = b.[ReturnStand])            [On Route Stand], ****


    COALESCE([ReturnKm], 0)                  AS [Distance of on route place],
   ( b.[DeadKm] + COALESCE([ReturnKm], 0) ) AS Total
    FROM   [dbo].[BreakDown] AS b
   INNER JOIN [dbo].[Bus Log] AS bl
           ON b.BusLogId = bl.Id
   INNER JOIN [dbo].[DriverAttendance] AS da
           ON da.Id = b.DrvrAttnDnceIdLog

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM