SUM和LEFTJOIN SQL

时间:2017-12-12 19:52:56

标签: sql-server tsql

我写这个查询

SELECT
    c.BID AS BID,
    c.BName AS BName,
    c.SName AS SName,
    CASE
       WHEN T.tHistoryValue1 = 1 THEN 'A'  
       WHEN T.tHistoryValue1 = 2 THEN 'B'
    END AS TType,
    COUNT(c.TID) AS TCount,
    MIN(c.TVaitTime) AS MinVTime,
    MAX(c.TVaitTime) AS MaxVTime,
    AVG(c.TVaitTime) AS AvVTime,
    MIN(c.TPTime) AS MinPTime,
    MAX(c.TPTime) AS MaxPTime,
    AVG(c.TPTime) AS AvPTime,
    AVG(CASE WHEN c.TPTime > 0 THEN c.TPTime ELSE 0 END) AS AvPTime, 
    result.ShowCount
FROM 
    c
LEFT JOIN
    (SELECT * 
     FROM cHistory 
     WHERE cHistoryTypeID = 4) AS T ON (T.TID = c.TID)
LEFT JOIN
    (SELECT SUM(CASE WHEN THistoryTypeId = 4 THEN 1 END) - 
            COUNT(CASE WHEN THistoryValue1 = 1 THEN 1 END) AS ShowCount 
     FROM tbl_THistory) AS result ON T.BID = c.BID
WHERE 
    c.TD = 0
GROUP BY 
    c.BName c.BID, c.SName, T.THistoryValue1, result.ShowCount
ORDER BY 
    c.BID, c.BName ASC

我收到此错误:

  

将表达式转换为数据类型int的算术溢出错误   警告:聚合或其他SET操作消除了空值。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

许多SQL函数返回INT并具有其他版本以返回BIGINT。 COUNT, for example, returns INTCOUNT_BIG。如果您认为您的值超过INT的值,请使用This is a good article on the NULL value。同样检查您的其他功能。

https://docs.microsoft.com/en-gb/nuget/Consume-Packages/Package-restore-troubleshooting