上次的简单的月报查询问题没弄懂,这次再来请教一下
我有表MeteTable
ID nDate EnvirTemp MaxEnvirTemp
1 2009-04-03 00:01:00 2.3 5.4
2 2009-04-03 01:01:00 2.3 5.4
3 2009-04-03 01:03:00 2.4 5.2
4 2009-04-03 02:00:00 2.4 5.2
5 2009-04-03 03:00:00 2.3 5.2
6 2009-04-03 04:00:00 2.6 3.2
7 2009-04-04 13:00:00 2.6 3.2
..........................................................
表面存放着一个月的数据,现在我需要将表里的整点数据及对应日期的最大值查询出来,如
行:小时整点 20(前一日的20点) 21 22 23 0 1 2 3.... 19(本日19点) Max(EnvirTemp)
列:
本月1日
本月2日
本月3日
.
.
.
.
.
.
本月31日
如果没有数据的,插入空占行
我问题是:
1、如果仅生成整点数据表,应该如何生成?每一日的数据仅查询出小时为整点的数据,如果查询出的数据为空,或日期为空就补空或空行(空行的日期那列还是要的,但其余数据为空)
如
行:小时整点 20(前一日的20点) 21 22 23 0 1 2 3.... 20(本日20点)
列:
本月1日
本月2日
本月3日
.
.
.
.
本月31日
2、如果生成下面的应该如何做呢?
行:小时整点 20(前一日的20点) 21 22 23 0 1 2 3.... 19(本日19点) Max(EnvirTemp)
======================================================================================================
------------------------------------------------------------------------
-- Author: happyflystone
-- Date : 2009-04-01 21:48:37
-- Ver: Microsoft SQL Server 2005 - 9.00.2047.00 (Intel X86)
-- Apr 14 2006 01:12:25
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Standard Edition on Windows NT 5.0 (Build 2195: Service Pack 4)
--
------------------------------------------------------------------------
-- Test Data: ta
IF OBJECT_ID('ta') IS NOT NULL
DROP TABLE ta
Go
CREATE TABLE ta(ID INT,nDate DATETIME,EnvirTemp NUMERIC(2,1),MaxEnvirTemp NUMERIC(2,1))
Go
INSERT INTO ta
SELECT 1,'2009-04-03 00:01:00',2.3,5.4 UNION ALL
SELECT 2,'2009-04-03 01:01:00',2.3,5.4 UNION ALL
SELECT 3,'2009-04-03 01:03:00',2.4,5.2 UNION ALL
SELECT 4,'2009-04-03 02:00:00',2.4,5.2 UNION ALL
SELECT 5,'2009-04-03 03:00:00',2.3,5.2 UNION ALL
SELECT 6,'2009-04-03 04:00:00',2.6,3.2 UNION ALL
SELECT 7,'2009-04-04 13:00:00',2.6,3.2
GO
--Start
select top 24 rid= identity(int,-4,1) into # from sysobjects
select top 30 rid= identity(int,0,1) into #2 from sysobjects
select d,rid into #1
from #
, (
select convert(char(10),ndate,120) as d
from ta group by convert(char(10),ndate,120)
) a
declare @s varchar(8000)
select @s = isnull(@s+',','')
+'['+ ltrim(case when rid < 0 then 24+rid else rid end)+']=
max(case when datediff(hh,ndate,'''+
convert(char(19),dateadd(hh,rid,cast(d as datetime)),120)+
''') = 0 then EnvirTemp else 0 end)' from #1
exec('select convert(char(10),ndate,120) as rq,'+ @s+'
from ta
group by convert(char(10),ndate,120) ')
drop table #,#1,#2
月报查询问题
最新推荐文章于 2025-04-18 00:01:12 发布