嵌套如果在select中

时间:2016-01-14 14:02:13

标签: sql sql-server tsql

如何组合这两个查询?

select e.UserId, count(*) as [Registrations], min(uas.UserId), min(uas.[TimeStamp])
from Ev as e 
    left join UAS as uas on e.UserId = uas.UserId
where e.EventTypeId = 3 and e.Value is not null 
group by e.UserId 
having count(*) >= 10

if not exists (select * from Ev as e left join UAS as uas
                   on e.UserId = uas.UserId where uas.UserId = e.UserId)
begin
    insert UAS values (12, '2013-05-31 15:54:14.963')
end;

我希望如果UAS表中不存在UserId,请插入它。

1 个答案:

答案 0 :(得分:0)

您可以使用WHERE NOT EXISTS

重写以下部分
if not exists (select * from Ev as e left join UAS as uas
                   on e.UserId = uas.UserId where uas.UserId = e.UserId)
begin
    insert UAS values (12, '2013-05-31 15:54:14.963')
end;

insert into UAS 
select 12, '2013-05-31 15:54:14.963'
from Test // Test is a dummy dual table
where not exists (
select 1 from Ev as e 
left join UAS as uas
on e.UserId = uas.UserId where uas.UserId = e.UserId )