0

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

第一个查询给出总数:

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 

得到上面的输出。没有共同的列名来连接这些第一个和第二个查询。

第一次查询的输出值每天都在变化,输出不是一直不变的值。

4

1 回答 1

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 
于 2013-07-25T04:01:49.103 回答