SQL服务器:如何在"where"子句中构造一个类似IF的系统?
SQL Server: how to construct a IF like system within "where" clause?
我有一个 table 在几次加入后像下面这样
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 的交易的总和和计数。
奖金:你想帮助我的另一个话题吗?其中我还需要有关索引的帮助:
determining the staff's title when a certain transaction is done
这里是:
使用 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
)
我有一个 table 在几次加入后像下面这样
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 的交易的总和和计数。
奖金:你想帮助我的另一个话题吗?其中我还需要有关索引的帮助:
determining the staff's title when a certain transaction is done
这里是:
使用 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
)