0

我有两种我希望能够加入的复杂查询,但不太确定执行它的语法。

查询一:

select month(Date_1) as Date_1, 
       sum(number_1) as number_1 
  from table_1 
  where Date_1 between '2012-01-01' and '2013-01-01' 
  group by month(Date_1);

这给出了这个结果:

在此处输入图像描述

查询 2:

select count(distinct number_2) as number_2, 
       month(Date_2) as Date_2 
  from table_2 
  where Date_2 between '2012-01-01' and '2013-01-01' 
  group by month(Date_2) 
  order by month(Date_2) desc;

这给出了这个结果:

在此处输入图像描述

我想加入这两个查询,以便当 Date_1 和 Date_2 列相等时 number_1 与 number_2 匹配。一个月一排。

有谁知道这是怎么做到的吗?

4

1 回答 1

1
select T1.Date_1, T1.number_1, T2.number_2 from 

(select month(Date_1) as Date_1, 
       sum(number_1) as number_1 
  from table_1 
  where Date_1 between '2012-01-01' and '2013-01-01' 
  group by month(Date_1))T1

inner join

(select count(distinct number_2) as number_2, 
       month(Date_2) as Date_2 
  from table_2 
  where Date_2 between '2012-01-01' and '2013-01-01' 
  group by month(Date_2) 
  order by month(Date_2) desc)T2

on T1.Date_1 = T2.Date_2;

本质上,在当月加入两个临时表(由查询形成)。

于 2013-01-07T15:42:14.587 回答