除以两列,但避免除以零

时间:2018-11-28 10:36:24

标签: sql-server

我想对连接日志表执行以下操作:

SELECT StartTime, EndTime, EventTime, SentBytes, SentObjects, \
    SentBytes/SentObjects AS bytes_per_object, \
    SentBytes/(EndTime - StartTime) AS bitrate, \
    (EndTime - StartTime) AS duration FROM [table];

但是在某些情况下,StartTime和EndTime可以相等(持续时间为零),或者SentObjects可以为零。因此,以上查询给出了除以零的误差。如何重写该语句,以便得到结果?用-1除以零是可以的。

我在想类似这种三元运算的方法,但是我不知道如何写:

SELECT IFF(SentObjects > 0, SentBytes/SentObjects, -1) AS bytes_per_object FROM table;

SELECT .... WHERE SentObjects > 0不是理想的解决方案,因为我想在一个列表中查看所有连接。

SQL Server版本10_50

6 个答案:

答案 0 :(得分:1)

    dwg = ezdxf.readfile("example.dxf")
    print "EXTMAX ", dwg.header['$EXTMAX']
    print "EXTMIN ", dwg.header['$EXTMIN']
    print "LIMMAX ", dwg.header['$LIMMAX']
    print "LIMMIN ", dwg.header['$LIMMIN']

您可以通过使用以下函数来避免为零

答案 1 :(得分:0)

SELECT StartTime, EndTime, EventTime, SentBytes, SentObjects, \
    SentBytes/SentObjects AS bytes_per_object, \
    isNull(SentBytes/nullif((EndTime - StartTime), 0), -1) AS bitrate, \
    (EndTime - StartTime) AS duration FROM [table];

答案 2 :(得分:0)

CASE
WHEN SentObjects > 0 THEN SentBytes/SentObjects
ELSE -1
END AS bytes_per_object

答案 3 :(得分:0)

您可以使用CASE WHEN...THEN...ELSE...END

SELECT StartTime, EndTime, EventTime, SentBytes, SentObjects,
    CASE WHEN SentObjects = 0 THEN -1 ELSE SentBytes/SentObjects END AS bytes_per_object,
    CASE WHEN EndTime = StartTime THEN -1 ELSE SentBytes/(EndTime - StartTime) END AS bitrate,
    (EndTime - StartTime) AS duration
FROM [table];

答案 4 :(得分:0)

SELECT StartTime, EndTime, EventTime, SentBytes, SentObjects,
    SentBytes/(case when isnull(SentObjects, 0) = 0 then -1 else SentObjects end) AS bytes_per_object,
    SentBytes/(case when isnull((EndTime - StartTime), 0) = 0 then -1 else (EndTime - StartTime)end) AS bitrate,
    (EndTime - StartTime) AS duration FROM [table];

答案 5 :(得分:0)

您还可以使用通用表表达式(CTE):(未经测试的脚本)

想法是要预先评估CTE中的列值,并在select语句中使用更新后的值。

;With CTE 
AS(
    SELECT StartTime, EndTime, EventTime, 
           IIF(SentObjects > 0, SentBytes, 1) AS SentBytesUpdated, \
           IIF(SentObjects > 0, SentObjects, -1) AS SentObjectsUpdated , \
           SentBytes/(EndTime - StartTime) AS bitrate, \
           (EndTime - StartTime) AS Duration \
    FROM [Table]
)SELECT StartTime, EndTime, EventTime, \
    SentBytesUpdated/SentObjectsUpdated AS bytes_per_object, \
    bitrate \
    Duration \
FROM [CTE]