select CBM_YM as 年月,CBM_City as城市,sum(CBM_PilCount) as 总数,sum(CBM_EngrossCount) as 占用数 from dbo.PIL_CountByMonth
group by CBM_YM,CBM_City出来的数据结构为年月 城市 总数 占用数
2009-9 北京 4 2
2009-9 无锡 5 2
2009-8 北京 4 3怎样才能实现这样的年月 城市 总数 占用数 城市 总数 占用数
2009-9 北京 4 2 无锡 5 2
2009-8 北京 4 3 null null null
group by CBM_YM,CBM_City出来的数据结构为年月 城市 总数 占用数
2009-9 北京 4 2
2009-9 无锡 5 2
2009-8 北京 4 3怎样才能实现这样的年月 城市 总数 占用数 城市 总数 占用数
2009-9 北京 4 2 无锡 5 2
2009-8 北京 4 3 null null null
-- Author :fredrickhu(我是小F,向高手学习)
-- Date :2009-10-19 13:50:44
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([年月] varchar(6),[城市] varchar(4),[总数] int,[占用数] int)
insert [tb]
select '2009-9','北京',4,2 union all
select '2009-9','无锡',5,2 union all
select '2009-8','北京',4,3
--------------开始查询--------------------------
select id=identity(int),* into # from tb
select a.年月,a.城市,a.总数,a.占用数,b.年月,b.城市,b.总数,b.占用数 from
(select * from # where 年月='2009-9')a
left join
(select * from # where 年月='2009-8')b
on
a.id=b.id-2
drop table #
----------------结果----------------------------
/* 年月 城市 总数 占用数 年月 城市 总数 占用数
------ ---- ----------- ----------- ------ ---- ----------- -----------
2009-9 北京 4 2 2009-8 北京 4 3
2009-9 无锡 5 2 NULL NULL NULL NULL(2 行受影响)
*/
这个ID我根本没法控制而且我要走1年的 有时候查询几个月的
哎呀 好麻烦 55555555
if object_id('tb')is not null drop table tb
gocreate table tb(年月 varchar(10),城市 varchar(10), 总数 int, 占用数 int)
insert tb select
'2009-9', '北京', 4 , 2 union all select
'2009-9', '无锡', 5 , 2 union all select
'2009-8', '北京', 4 , 3 declare @s varchar(4000)select @s=isnull(@s+',','')
+'max(case when 城市='''+城市+''' then 城市 else null end) [城市],'
+'max(case when 城市='''+城市+''' then 总数 else null end) [总数],'
+'max(case when 城市='''+城市+''' then 占用数 else null end) [占用数]'
from (select distinct 城市 from tb)tset @s='select 年月,'+@s+' from tb group by 年月'
exec(@s)
年月 城市 总数 占用数 城市 总数 占用数
---------- ---------- ----------- ----------- ---------- ----------- -----------
2009-8 北京 4 3 NULL NULL NULL
2009-9 北京 4 2 无锡 5 2
警告: 聚合或其他 SET 操作消除了空值。(2 行受影响)