我在表中插入了一些值,同时保存了插入变量中的行数,
declare @tempinsertcount int
set @tempinsertcount = 0
insert into #tempTable (Time, terminal_id, claims)
select
Time, terminal_id, claims
from
Claims as c
join
(select
min(Time) as mintime, dateadd(mi,-60,min(Time) as hrprior, terminal_id
from
#tempTable
group by
terminal_id) as temp on c.terminal_id = temp.terminal_id
and c.[Time] > temp.hrprior
set @tempinsertcount = @tempinsertcount+ @@ROWCOUNT
我的插入值(输出)将是这样的,
Time terminal_id claims
-----------------------------------------------------
2017-04-19 23:59:00 8 147
2017-04-19 23:59:00 9 87
2017-04-19 23:59:00 10 284
2017-04-20 00:00:00 8 148
2017-04-20 00:00:00 9 88
2017-04-20 00:00:00 10 285
2017-04-20 00:01:00 8 149
2017-04-20 00:01:00 9 89
2017-04-20 00:01:00 10 286
上面有9行插入。我select @tempinsertcount
得到9并且工作正常。
然而,当我尝试将terminal_id
的计数保存在变量中时,该变量将是3个ID(每个中的一个)。我尝试了以下(我的整个查询),
declare @tempinsertcount int
set @tempinsertcount = 0
declare @termidcount nvarchar
set @termidcount = 0
insert into #tempTable (Time, terminal_id, claims)
select Time, terminal_id, claims
from Claims as c
join (
select min(Time) as mintime, dateadd(mi,-60,min(Time) as hrprior, terminal_id
from #tempTable
group by terminal_id
) as temp
on c.terminal_id = temp.terminal_id and c.[Time] > temp.hrprior
set @tempinsertcount = @tempinsertcount + @@ROWCOUNT
set @termidcount = (select count(terminal_id) --, terminal_id
from #tempTable
group by terminal_id
)
select @termidcount
select @tempinsertcount
在这里,我收到了@termidcount
变量的错误,
子查询返回的值超过1。这是不允许的 子查询跟随=,!=,<,< =,>,> =或当子查询用作 表达。
我知道,根据我的查询,我试图在变量中保存多个值。如何实例化@termidcount
变量获取ID计数?
答案 0 :(得分:3)
您可以轻松完成以下操作
<强>解释强>
您可以使用count distinct
在一个查询中同时获取总行数和不同的terminal_id计数查询
select count(*), count(distinct terminal_id)
from #tempTable
这是一个有效的demo
希望这会对你有所帮助
答案 1 :(得分:0)
你应该改变你的sql代码
&#xA;&#xA; 设置@termidcount =(select count(terminal_id) - ,terminal_id&#xA;来自#tempTable&#xA; group by terminal_id&#xA;)&#xA;
&#xA;&#xA; to
&#xA;&#xA; set @termidcount =(从#tempTable中选择COUNT(DISTINCT terminal_id))&#xA;
&#xA;