日期:2014-05-16 浏览次数:20659 次
----------------------------------------------------------------
-- Author :DBA_HuangZJ(发粪涂墙)
-- Date :2014-04-24 08:19:43
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64)
-- Apr 2 2010 15:48:46
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据@a
declare @a table([区域] nvarchar(4),[类型] nvarchar(2),[金额] int,[日期] datetime)
insert @a
select N'华北',N'买',3500,'2013.3.25' union all
select N'西北',N'卖',2500,'2013.3.24' union all
select N'东北',N'买',1200,'2013.3.25' union all
select N'华北',N'卖',2000,'2013.3.23' union all
select N'东北',N'卖',200,'2013.3.25' union all
select N'华北',N'买',10000,'2013.3.29'
--------------生成数据--------------------------
select [区域],SUM([金额])[金额],count(CASE WHEN [类型]=N'买' THEN 1 ELSE NULL END )'买的次数',
count(CASE WHEN [类型]=N'卖' THEN 1 ELSE NULL END )'卖的次数'
from @a
GROUP BY [区域]
----------------结果----------------------------
/*
区域 金额 买的次数