34,590
社区成员
发帖
与我相关
我的任务
分享
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([id] nvarchar(8),[时间] datetime,[总量] int)
insert [huang]
select 'M001','2013-10-01 00:30:00',238 union all
select 'M001','2013-10-01 01:30:00',252 union all
select 'M001','2013-10-01 02:30:00',276 union all
select 'M002','2013-10-01 12:00:00',1002 union all
select 'M002','2013-10-01 13:30:00',1230 union all
select 'M002','2013-10-01 18:00:00',1520
--------------生成数据--------------------------
SELECT id,[时间],SUM([总量])[总量]
FROM (
select id,[时间],[总量]
from [huang]
WHERE CONVERT(VARCHAR(10),[时间],120) BETWEEN '2013-10-01' AND '2013-11-20'
AND CONVERT(VARCHAR(10),[时间],108)='18:00:00'
UNION ALL
select id,[时间],-1*[总量]
from [huang]
WHERE CONVERT(VARCHAR(10),[时间],120) BETWEEN '2013-10-01' AND '2013-11-20'
AND CONVERT(VARCHAR(10),[时间],108)='12:00:00'
)a
GROUP BY id,[时间]
HAVING SUM([总量])>600
/*
id 时间 总量
-------- ----------------------- -----------
M002 2013-10-01 18:00:00.000 1520
*/
select ID,日期 from 表 where
CONVERT(VARCHAR(10),[时间],120) BETWEEN '2013-10-01' AND '2013-11-20'
AND CONVERT(VARCHAR(10),[时间],108) BETWEEN '12:00:00' AND '18:00:00'
and 总量>600
----------------------------------------------------------------
-- Author :DBA_HuangZJ(发粪涂墙)
-- Date :2014-03-07 13:27:44
-- 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)
--
----------------------------------------------------------------
--> 测试数据[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([id] nvarchar(8),[时间] datetime,[总量] int)
insert [huang]
select 'M001','2013-10-01 00:30:00',238 union all
select 'M001','2013-10-01 01:30:00',252 union all
select 'M001','2013-10-01 02:30:00',276 union all
select 'M002','2013-10-01 00:30:00',1002 union all
select 'M002','2013-10-01 13:30:00',1230 union all
select 'M002','2013-10-01 17:30:00',1520
--------------生成数据--------------------------
select id,[时间]
from [huang]
WHERE CONVERT(VARCHAR(10),[时间],120) BETWEEN '2013-10-01' AND '2013-11-20'
AND CONVERT(VARCHAR(10),[时间],108) BETWEEN '12:00:00' AND '18:00:00'
GROUP BY id,[时间]
HAVING SUM([总量])>600
----------------结果----------------------------
/*
id 时间
-------- -----------------------
M002 2013-10-01 13:30:00.000
M002 2013-10-01 17:30:00.000
*/