日期:2014-05-16 浏览次数:20547 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-02-19 08:48:11
-- 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]([日期] datetime,[客户名] varchar(4),[类型] varchar(2),[排名] int,[进货额] int,[出货额] int)
insert [huang]
select '20140208','张三','进',1,1322,1000 union all
select '20140208','李四','进',2,1111,2 union all
select '20140208','赵武','进',3,200,37 union all
select '20140208','王二','出',1,1,3000 union all
select '20140208','张三','出',2,1322,1000 union all
select '20140208','刘九','出',3,11,600
--------------开始查询--------------------------
SELECT *
FROM (
select [日期],[类型],SUM( [进货额] )[进货总额],SUM( [出货额] )[出货总额]
FROM huang
WHERE [类型]='进'
GROUP BY [日期],[类型]
UNION ALL
select [日期],[类型],SUM( [进货额] )[进货总额],SUM( [出货额] )[出货总额]
FROM huang
WHERE [类型]='出'
GROUP BY [日期],[类型]
UNION ALL
SELECT [日期],'全' [类型],SUM([进货额]),SUM([出货额])
FROM (SELECT DISTINCT [日期],[进货额],[出货额] FROM [huang])a
GROUP BY [日期])a
ORDER BY [日期],CASE 类型 WHEN '进' THEN 1 WHEN '出' THEN 2 ELSE 3 END
----------------结果----------------------------
/*
日期 类型 进货总额 出货总额
----------------------- ---- ----------- -----------
2014-02-08 00:00:00.000 进 2633 &n