使用另一个表中一个表的计数

时间:2012-10-11 13:11:43

标签: sql-server-2008

所以我已经在#table1中计算了一个数字,我希望在另一个我创建的表中显示。 所以第一次计数的语法是

select COUNT(*)
into #table1
from #test8
where account_number1 is null
GROUP BY varmonth,MONYEAR
ORDER BY varmonth, MONYEAR

然后第二个表是

SELECT MONYEAR, 
COUNT(*) AS TOTAL,
SUM(CURRENT_BALANCE_AMOUNT) REH_BAL,
FROM #table1
WHERE ROWNUMBER = 1 
GROUP BY varmonth,MONYEAR
ORDER BY varmonth, MONYEAR

但是我希望第一个计数在第二个表中的计数和总和之间滑动。 有没有办法这样做所有数字输出在一个决赛桌? 感谢

1 个答案:

答案 0 :(得分:1)

你可以这样做:

SELECT
  t2.MONYEAR,
  t2.Total,
  t1.tcount,
  t2.REH_BAL
FROM
(
  select varmonth, MONYEAR, COUNT(*) tcount
  from #test8
  where account_number1 is null 
  GROUP BY varmonth,MONYEAR
) t1
INNER JOIN
(
  SELECT MONYEAR, 
    COUNT(*) AS TOTAL,
    SUM(CURRENT_BALANCE_AMOUNT) REH_BAL,
  FROM #table1
  WHERE ROWNUMBER = 1 
  GROUP BY varmonth,MONYEAR
) t2 ON t1.MONYEAR = t2.MONYEAR
ORDER BY t1.varmontth, t2.MONYEAR