在union max和min sql语句之后获取数据

时间:2015-02-27 22:03:47

标签: sql vb.net max union min

有没有办法在一个语句中组合这些sql语句:

   Dim s As String = 
   "SELECT  byu,MAX(atttime) AS attime FROM att 
    WHERE pno='" + DataGridView1.Rows(i).Cells(0).Value.ToString + "' 
    and attdate ='" + curdate + "' and atttime>='" + mxtime + "'
    and atttime<='" + mxtime2 + "' "


  Dim xmd As New SqlCommand(s, con)
  Dim dr As SqlDataReader = xmd.ExecuteReader
  If dr.Read Then
     DataGridView1.Rows(i).Cells(7).Value = dr("attime")
     DataGridView1.Rows(i).Cells(14).Value = dr("byu")
  End If
     dr.close
   Dim s2 As String =
     "SELECT byu, MIN(atttime) AS attime FROM att 
     WHERE pno='" + DataGridView1.Rows(i).Cells(0).Value.ToString + "' 
    and attdate ='" + curdate + "' and atttime>='" + mintime + "'
    and atttime<='" + mintime2 + "' "
  Dim xmd2 As New SqlCommand(s2, con)
  Dim dr2 As SqlDataReader = xmd2.ExecuteReader
  If dr2.Read Then
  DataGridView1.Rows(i).Cells(4).Value = dr2("attime")
  DataGridView1.Rows(i).Cells(15).Value = dr2("byu")
  End If
  dr2.Close()   

表格att的数据为:

  pno   attdate     atttime   byu
   2    2015/01/02  07:05:02   0 
   2    2015/01/02  07:07:02   1 
   2    2015/01/02  18:08:11   0
   2    2015/01/02  19:15:02   1

我从早上开始尝试并没有提出一些问题,当我联合2 sql语句时,我无法获得MAX(atttime)的“byu”以及MIN的“byu”( atttime)通过SqlDataReader。我几乎把网站上与此相关的所有问题都解决了,到目前为止我没有任何工作。上面代码的结果是:

2     2015/01/02    07:05:02   0
2     2015/01/02    19:15:02   1

请帮忙,谢谢。

1 个答案:

答案 0 :(得分:0)

您可以加入这样的查询并将其作为批处理语句执行

Dim s As String = 
   "SELECT byu as byu1,MAX(atttime) AS attime1 FROM att 
   WHERE pno='" + DataGridView1.Rows(i).Cells(0).Value.ToString + "' 
   and attdate ='" + curdate + "' and atttime>='" + mxtime + "'
   and atttime<='" + mxtime2 + "' group by byu ;" +
   "SELECT byu as byu2,MIN(atttime) AS attime2 FROM att 
   WHERE pno='" + DataGridView1.Rows(i).Cells(0).Value.ToString + "' 
   and attdate ='" + curdate + "' and atttime>='" + mintime + "'
   and atttime<='" + mintime2 + "' group by byu ;"

这是唯一的想法,我不知道你从数据库中获得了多少列,你必须设置你的cell()值分别是从数据库获得的列顺序

Dim xmd As New SqlCommand(s, con)
Dim dr As SqlDataReader = xmd.ExecuteReader
  If dr.Read Then
     DataGridView1.Rows(i).Cells(7).Value = dr("attime1")
     DataGridView1.Rows(i).Cells(14).Value = dr("byu1")
     DataGridView1.Rows(i).Cells(4).Value = dr("attime2")
     DataGridView1.Rows(i).Cells(15).Value = dr("byu2")
  End If