【问题标题】:SQL Server: how to construct a IF like system within "where" clause?SQL Server:如何在“where”子句中构造一个类似 IF 的系统?
【发布时间】:2020-06-01 14:28:36
【问题描述】:

在几次加入后我有一个如下表

username    trandate    positionname       ChannelID
--------    ----        ------------       ---------
system      01/01/2019                     1
anderson    06/04/2019  chief              1
williams    07/03/2019  chief              2
julie       15/02/2019  technician         48
julie       27/05/2019  chief technician   21

我想计算交易总数,按月、年和渠道类型分组的金额总和。

有一个条件:如果 channelID 等于“1”,则查询应排除 (1) “positionname”为空值的事务或 (2) 具有“system”用户名的事务。

我的代码如下所示:

    select DISTINCT

DATEPART(YEAR,a.TranDate) as [year],
DATEPART(MONTH,a.TranDate) as [month],

    count(*) as [transaction number], 
    sum(a.Amount) as [Total amount], 

    b.Name as [branch name], 
    c.ChannelName as [channel] 

    from transactions_main as a

left join branches      as b    WITH (NOLOCK) ON a.TranBranch=b.BranchId  
left join Channels      as c    WITH (NOLOCK) ON a.ChannelId=c.ChannelId  
left join Staff_Info    as d    WITH (NOLOCK) ON a.UserName=d.UserCode 

where 
        a.TranDate>'20181231' 
        and b.name not in ('HQ')
        and (a.ChannelId=1 
            and d.positionname is not null 
            and a.UserName not in ('SYSTEM', 'auto') ) 


            group by b.Name, c.ChannelName,DATEPART(YEAR,a.TranDate), DATEPART(MONTH,a.TranDate) 

order by b.Name, Year,month

最后,当然,它没有工作。我得到了只有 channelID=1 的事务的总和和计数。

奖励:你想帮助我的另一个话题吗?其中我还需要有关索引的帮助:

当某笔交易完成时确定员工的头衔

这里是:link

【问题讨论】:

  • 删除a.ChannelId = 1,您可能会获得更多频道。

标签: sql sql-server ssms-2012


【解决方案1】:

使用 OR 运算符

where 
        a.TranDate>'20181231' 
        and b.name not in ('HQ')
        and (   
                (a.ChannelId=1 
                and d.positionname is not null 
                and a.UserName not in ('SYSTEM', 'auto') ) 
                )
                OR
                a.ChannelId<>1 
            )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 2023-03-21
    相关资源
    最近更新 更多