从表1的计数结果中减去表2中的每一行

时间:2013-07-25 03:58:26

标签: sql-server-2008-r2

基本上我有两个查询输出:

第一个查询给出总计数:

select COUNT(*) as 'TotalStudents' from StudentLists 

这给出了一个计数输出,比如50。

第二次查询:

CREATE TABLE #TMP(week_date date,cused int)
insert into #TMP(cused ,week_date)
select *  
from
(select studentid, clientdate
  from table1 where DATEDIFF(DAY,clientdate,GETDATE()) <= 7
  union 
  select studentid, DATE
  from table2 where DATEDIFF(DAY,DATE,GETDATE()) <= 7 
 ) a 

 select week_date ,COUNT(distinct cused )as 'Totalcused ' from #TMP 
 group by week_date 

第二个查询将输出显示为:

week_date   Totalcused 
2013-07-18  11
 2013-07-19 18
2013-07-20  23
2013-07-22  9
2013-07-23  19

现在,我想在query1中减去每个用totalstudents包含的行。

我的预期输出应该是,

week_date   Totalcused nused
2013-07-18  11        39
 2013-07-19 18        32
2013-07-20  23        27
2013-07-22  9         41
2013-07-23  19        31

如何将第一个查询结果合并到此查询中:

 select week_date ,COUNT(distinct cused )as 'Totalcused ' from #TMP 
 group by week_date 

获得上述输出。 没有通用的列名来加入这些第一和第二个查询。

第一个查询输出值将每天不断变化,输出始终不是常量值。

1 个答案:

答案 0 :(得分:2)

将Total分配给变量,并在第二个查询中使用它。

这样的东西
DECLARE @Total INT

select @Total = COUNT(*) from StudentLists 

CREATE TABLE #TMP(week_date date,cused int)
insert into #TMP(cused ,week_date)
select *  
from
(select studentid, clientdate
  from table1 where DATEDIFF(DAY,clientdate,GETDATE()) <= 7
  union 
  select studentid, DATE
  from table2 where DATEDIFF(DAY,DATE,GETDATE()) <= 7 
 ) a 

 select week_date ,
        COUNT(distinct cused )as 'Totalcused ', 
        @Total - COUNT(distinct cused ) as 'nused'  
 from #TMP 
 group by week_date