日期:2014-05-16 浏览次数:20526 次
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-31 14:34:30
-- Verstion:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([日期] datetime,[名称] varchar(4),[数量] int,[箱数] int)
insert [tb]
select '2014-1-1','花生',20,2 union all
select '2014-1-1','苹果',40,2 union all
select '2014-1-1','香蕉',10,1 union all
select '2014-1-2','梨',30,3 union all
select '2014-1-2','苹果',20,1 union all
select '2014-1-3','花生',10,1 union all
select '2014-1-4','香蕉',20,2
--------------开始查询--------------------------
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+'sum(case when [日期]='+quotename(日期,'''')+' then [数量] else 0 end)['+CONVERT(VARCHAR(10),日期,120)+'数量]'
+',sum(case when [日期]='+quotename(日期,'''')+' then [箱数] else 0 end)['+CONVERT(VARCHAR(10),日期,120)+'箱数]'
from tb group by 日期
EXEC('select [名称]'+@s+',sum(数量) as 数量合计,sum(箱数) as 箱数合计 from tb group by [名称]')
----------------结果----------------------------
/* 名称 2014-01-01数量 2014-01-01箱数 2014-01-02数量 2014-01-02箱数 2014-01-03数量 2014-01-03箱数 2014-01-04数量 2014-01-04箱数 数量合计 箱数合计
---- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ----------- -----------
花生 20 2 0 0 10 1 0 0 30 3
梨 0 0 30