T-SQL Sum IIf查询

时间:2016-07-11 12:04:59

标签: sql sum

    SELECT t1.detail_Date AS clmDate
    ,t1.detail_agentID AS clmPID
    ,t3.HODCode AS clmHOD
    ,t1.detail_CallsHandled AS clmIBConnects
    ,t1.detail_TalkTime AS clmIBTalk
    ,t1.detail_WrapTime AS clmIBWrap
    ,t1.detail_HoldTime AS clmIBHold
    ,t1.detail_HandleTime AS clmIBTotal
    ,Sum(IIf([fldCallRoute.Value] = [Inbound],0)) AS clmIBConnects
--  ,Sum(IIf([fldCallRoute] = "Inbound", [clmTalk], 0)) AS IBTalk
--  ,Sum(IIf([fldCallRoute] = "Inbound", [clmWrap], 0)) AS IBWrap
--  ,Sum(IIf([fldCallRoute] = "Inbound", [clmTalk] + [clmWrap] + [clmHold], 0)) AS IBTotal
    ,Sum(0) AS clmOBSignedOn
    ,Sum(0) AS Preview
    ,Sum(0) AS OBTalk
    ,Sum(0) AS OBUpdate
    ,Sum(0) AS OBWork
    ,Sum(0) AS OBConnects
--  ,Sum(IIf([fldCallRoute] = "Inbound", [clmHold], 0)) AS IBHold
--  ,Sum(IIf([fldCallRoute] = "Outbound", [clmHold], 0)) AS OBHold}

我没有得到总和(iif ..部分查询更具体: ,Sum(IIf([fldCallRoute] = "Inbound", [clmIBConnects], 0)) AS clmIBConnects

它显示无效的列名称'Inbound'无效列名'clmIBConnects'?

fldCallRoute列位于表t2中,其中包含条目入站,所以我不确定为什么它会说列名入站?

2 个答案:

答案 0 :(得分:3)

字符串常量需要单引号:

Sum(IIf([fldCallRoute] = 'Inbound', [clmTalk], 0)) AS IBTalk,

我优先选择case而不是iif()case是ANSI标准,几乎在所有数据库中都可用:

SUM(CASE WHEN fldCallRoute = 'Inbound' THEN clmTalk ELSE 0 END) as IBTalk,

答案 1 :(得分:1)

您需要对字符串使用单引号'。双引号"表示一列,通常用于保留字:

,Sum(IIf([fldCallRoute] = 'Inbound', [clmIBConnects], 0)) AS clmIBConnects

您还有6列评估为Sum(0),始终为0 ..错字?