我正在运行以下脚本 -
declare @eventname VARCHAR(64)
declare @eventid INT
set @eventname = 'event123'
set @eventid = (select tm.trgmst_id from trgmst tm where tm.trgmst_name = @eventname)
declare @trgjobmax INT
set @trgjobmax = (select max(trgjob_id) from trgjob)
declare @jobid TABLE (jobmst_id INT, trgjob_order INT)
insert into @jobid (jobmst_id, trgjob_order)
select
jm.jobmst_id, max(tj.trgjob_order)
from
jobmst jm
left outer join
trgjob tj on tj.jobmst_id = jm.jobmst_id
inner join
workgrp wg on wg.workgrp_id = jm.jobmst_owner
where
wg.workgrp_name in ('group1', 'group2', 'group3')
and jm.jobmst_type = 2
and jm.jobmst_dirty <> 'X'
and jm.jobmst_id NOT IN (select tj.jobmst_id
from trgjob tj
where tj.trgmst_id = @eventid)
group by
jm.jobmst_id
order by
jm.jobmst_id desc
问题是我收到了这条消息 -
警告:聚合或其他SET消除了空值 操作
原因是它并不总是保证具有trgjob_order值,因此它显示为NULL。然后我必须在同一个事务中运行以下更新脚本,它似乎工作正常。
update @jobid
set trgjob_order = 0
where trgjob_order IS NULL
有没有办法更优雅地写这个?我给出的数据看起来是正确的,所以我只是采取警告......这是一个警告,但可以忽略,因为我正在进行更新POST以替换NULL 0
答案 0 :(得分:3)
使用ISNULL
select jm.jobmst_id, ISNULL(max(tj.trgjob_order), 0) from jobmst jm
完整的脚本
declare @eventname VARCHAR(64)
declare @eventid INT
set @eventname = 'event123'
set @eventid = (select tm.trgmst_id from trgmst tm where tm.trgmst_name = @eventname)
declare @trgjobmax INT
set @trgjobmax = (select max(trgjob_id) from trgjob)
declare @jobid TABLE (jobmst_id INT, trgjob_order INT)
insert into @jobid (jobmst_id, trgjob_order)
select jm.jobmst_id, ISNULL(max(tj.trgjob_order), 0) from jobmst jm
left outer join trgjob tj on tj.jobmst_id = jm.jobmst_id
inner join workgrp wg on wg.workgrp_id = jm.jobmst_owner
where wg.workgrp_name in ('group1', 'group2', 'group3')
and jm.jobmst_type = 2 and jm.jobmst_dirty <> 'X' and jm.jobmst_id
NOT IN (
select tj.jobmst_id from trgjob tj
where tj.trgmst_id = @eventid
)
group by jm.jobmst_id
order by jm.jobmst_id desc
答案 1 :(得分:0)
我认为你想要的是MAX(ISNULL(Column,0))而不是ISNULL(MAX(Column),0),这将在聚合之前删除null。
在这种情况下,使用MAX可以正常工作,但小心地使用COUNT执行此操作,因为它会产生不同的结果(给定null不计算且ISNULL的值为)