[英]SQL Server: how to construct a IF like system within “where” clause?
几次加入后,我有一张如下表
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”上具有 null 值的事务或(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 的事务的总和和计数。
奖金:你想帮助我的另一个话题吗? 在其中我还需要有关索引的帮助:
当某笔交易完成时确定员工的头衔
这是: 链接
使用 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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.