日期:2014-05-17  浏览次数:20465 次

求按日期分组后组内按条件输出的sql语句
假设有表
时间      省份  数据
2013-8-1  陕西  50
2013-8-2  陕西  50
2013-8-3  陕西  50
2013-8-3  河南  50
2013-8-4  陕西  50
2013-8-5  陕西  50
2013-8-5  河南  50
2013-8-5  山西  50
要求输出结果为
时间        全国  陕西  山西  河南
2013-8-1    50     50     0    0
2013-8-2    50     50     0    0
2013-8-3   100     50     0   50
2013-8-4    50     50     0    0
2013-8-5   150     50    50   50
------解决方案--------------------
create table tb(时间 datetime,省份 varchar(20),  数据 int)

insert into tb
select '2013-8-1',  '陕西',  50 union all
select '2013-8-2',  '陕西',  50 union all
select '2013-8-3',  '陕西',  50 union all
select '2013-8-3',  '河南',  50 union all
select '2013-8-4',  '陕西',  50 union all
select '2013-8-5',  '陕西',  50 union all
select '2013-8-5',  '河南',  50 union all
select '2013-8-5',  '山西',  50
go


declare @sql varchar(8000)

set @sql = ',sum(数据) as [全国]'

select @sql = @sql + ',sum(case when 省份='''+省份+''' then 数据 else 0 end) ['+省份+']'
from tb
group by 省份
order by 省份 desc

select @sql = 'select 时间'+@sql +
              'from tb group by 时间'

exec( @sql)
/*
时间 全国 陕西 山西 河南
2013-08-01 00:00:00.000 50 50 0 0
2013-08-02 00:00:00.000 50 50 0 0
2013-08-03 00:00:00.000 100 50 0 50
2013-08-04 00:00:00.000 50 50 0 0
2013-08-05 00:00:00.000 150 50 50 50
*/

------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2014-01-22 14:07:39
-- Version:
--      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
-- Dec 28 2012 20:23:12 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([时间] date,[省份] varchar(4),[数据] int)
insert [huang]
select '2013-8-1','陕西',50 union all
select '2013