4,816
社区成员
![](https://csdnimg.cn/release/cmsfe/public/img/topic.427195d5.png)
![](https://csdnimg.cn/release/cmsfe/public/img/me.40a70ab0.png)
![](https://csdnimg.cn/release/cmsfe/public/img/task.87b52881.png)
![](https://csdnimg.cn/release/cmsfe/public/img/share-circle.3e0b7822.png)
--> 测试数据:#tb1
if object_id('tempdb.dbo.#tb1') is not null drop table #tb1
create table #tb1
(
日期 datetime ,
产量 int ,
单位 varchar(50)
)
insert into #tb1
select '2010-9-1',100,'一部' union all
select '2010-9-2',122,'二部' union all
select '2010-9-3',133,'三部' union all
select '2010-9-4',144,'一部'
--> 测试数据:#tb2
if object_id('tempdb.dbo.#tb2') is not null drop table #tb2
create table #tb2
(
日期时间 datetime ,
事故数量 int ,
单位 varchar(50)
)
insert into #tb2
select '2010-9-1 00:1:12',1,'一部' union all
select '2010-9-1 05:4:43',1,'二部' union all
select '2010-9-2 07:2:43',1,'三部' union all
select '2010-9-2 03:6:43',1,'一部'
--> SQL查询
select T1.月份,一部产量,一部事故数量,二部产量,二部事故数量,三部产量,三部事故数量
from
(
select Month(日期) as 月份,
sum(case 单位 when '一部' then 产量 else 0 end) 一部产量,
sum(case 单位 when '二部' then 产量 else 0 end) 二部产量,
sum(case 单位 when '三部' then 产量 else 0 end) 三部产量
from #tb1
group by Month(日期)) T1,
(
select Month(日期时间) as 月份,
sum(case 单位 when '一部' then 事故数量 else 0 end) 一部事故数量,
sum(case 单位 when '二部' then 事故数量 else 0 end) 二部事故数量,
sum(case 单位 when '三部' then 事故数量 else 0 end) 三部事故数量
from #tb2
group by Month(日期时间)) T2
where T1.月份=T2.月份
--> 结果
月份 一部产量 一部事故数量 二部产量 二部事故数量 三部产量 三部事故数量
----------- ----------- ----------- ----------- ----------- ----------- -----------
9 244 2 122 1 133 1
(1 行受影响)