我有个表:用来存储水表上的数字,每天都抄表,然后有一个数字录入,假如只有三块水表就像这样:
流水号  表号  表上数字   记录时间
  1      1      1000      2004-10-10
  2      2      200       2004-10-10
  3      3      300       2004-10-10
  4      1      1500      2004-10-11
  5      2      800       2004-10-11
  6      3      1000      2004-10-11
  7      1      1800      2004-10-12
  8      2      1200      2004-10-12
  9      3      1500      2004-10-12如果我想查到某天所有水表上走过的数字(消耗的水),比如要查找2004-10-11或2004-10-12这一天三块表的,如何查,那么如果我想查到2004-10-10到2004-10-12,也就是11、12 号两天分别的用水量,如何查,我想了方案,最后的问题还是落到这里的这样的查询语句上,所以恳请帮忙,小弟感激不尽。每天的记录是晚上下班或换班的时侯记录的,比如,晚上10点下班,从昨天晚上10点到今天晚上10点都是算今天的,今天晚上10点这个数字减去昨天晚上10点那个数字,就是今天的用水--查询的存储过程
create proc p_qry
@dt_begin datetime=null,--如果指定为null,表示查询今天的数据
@dt_end datetime=null --如果指定为null,表示和 @dt_begin 相同
as
set nocount on
if @dt_begin is null set @dt_begin=convert(char(10),getdate(),120)
if @dt_end is null set @dt_end=@dt_beginselect 记录时间=convert(char(10),a.记录时间,120)
,消耗的水=isnull(a.表上数字,0)-isnull(b.表上数字,0)
from tb a
left join tb b on a.表号=b.表号 and a.记录时间=dateadd(day,1,b.记录时间)
where a.记录时间 between @dt_begin and @dt_end
go
我不会用存储过程,我想用一个过程替代这个存储过程,我是在vb中用的,如何写?看我写一个,帮忙看看:
private sub aa(byval dt_begin as date,byval dtend as date)
   dim str as string
   dim rst adodb.recorderset
   rst="select a.表号,记录时间=convert(char(10),a.记录时间,120),消耗的水=isnull(a.表上数字,0)-isnull(b.表上数字,0) from tb a left join tb b on a.表号=b.表号 and a.记录时间=dateadd(day,1,b.记录时间)"---------假设这个字符串在vb中并没有换行
where a.记录时间 between @dt_begin and @dt_end
   if executeSQL(str,rst)=true then
      dagri.datasource=rst
   end
end sub

解决方案 »

  1.   

    dim strsql as string
    strsql="select a.表号,记录时间=convert(char(10),a.记录时间,120)," _
          & "消耗的水=isnull(a.表上数字,0)-isnull(b.表上数字,0) " _
          & "from tb a left join tb b " _
          & "on a.表号=b.表号 and a.记录时间=dateadd(day,1,b.记录时间) " _
          & "where a.记录时间 between '"& @dt_begin &"' and '"& @dt_e &"'  "
      

  2.   

    tb: 
    ID  表号  表上数字   记录时间
    1 1 1000 2004-09-01
    2 2 1000 2004-09-01
    3 3 1000 2004-09-01
    4 1 1500 2004-09-02
    5 2 1600 2004-09-02
    6 3 1700 2004-09-02
    7 1 2100 2004-09-03
    8 2 2600 2004-09-03
    9 3 3000 2004-09-03Create Proc usp_GetInfo
         @BeginDate char(10),
         @EndDate char(10)
    As
    select A.记录时间,A.表号,(A.表上数字-B.表上数字)AS 耗量
        from tb A,tb B
    Where A.记录时间 between @BeginDate AND @EndDate 
        AND B.记录时间 between Convert(char(10),DateAdd(day,-1,@BeginDate),120) 
            AND Convert(char(10),DateAdd(day,-1,@EndDate),120)
        AND A.表号=B.表号 And A.记录时间=Convert(char(10),DateAdd(day,1,B.记录时间),120)
    Group by A.记录时间,A.表号,A.表上数字,B.表上数字exce usp_GetInfo '2004-09-02','2004-09-03'结果
    2004-09-02 1 500
    2004-09-02 2 600
    2004-09-02 3 700
    2004-09-03 1 600
    2004-09-03 2 1000
    2004-09-03 3 1300
      

  3.   

    修改一下
    exec usp_GetInfo '2004-09-02','2004-09-03'细节你自己处理一下