日期:2014-05-17 浏览次数:20437 次
----------------------------
-- Author :DBA_Huangzj
-- Date :2013-01-08 19:34:08
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
-- Jun 17 2011 00:54:03
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([username] varchar(4),[type] varchar(7),[createtime] datetime,[renmit] int)
insert [huang]
select '张山','cashin','2012-12-01 00:00:00',1000 union all
select '李四','cashout','2012-12-01 00:00:00',1000 union all
select '王五','cashin','2012-12-01 00:00:00',1000
--------------开始查询--------------------------
SELECT SUM(renmitout)renmitout,SUM(renmitint)renmitint,SUM(renmitout)-SUM(renmitint)
FROM (
select SUM(renmit)renmitout,0 renmitint
from [huang]
WHERE [createtime] BETWEEN CONVERT(VARCHAR(10),[createtime],120)+' 00:00:00.000' AND CONVERT(VARCHAR(10),[createtime],120)+' 23:59:59.997'
AND [type]='cashout'
UNION ALL
select 0 renmitout,SUM(renmit) renmitint
from [huang]
WHERE [createtime] BETWEEN CONVERT(VARCHAR(10),[createtime],120)+' 00:00:00.000' AND CONVERT(VARCHAR(10),[createtime],120)+' 23:59:59.997'
AND [type]='cashin')a
----------------结果----------------------------
/*
renmitout renmitint
----------- ----------- -----------
1000 2000 -1000
(1 行受影响)
*/
USE test
GO