【发布时间】: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