VB.NET Database Query to Chart a Quantity Vs Date - sql

I have a table in an Access database with information like the following:
DATE SERIAL RESULT
1/5/2016 5299 PASS
1/5/2016 5371 PASS
1/6/2016 5280 PASS
1/6/2016 3962 FAIL
1/7/2016 1325 PASS
I'm trying to run a query to display a count of the SERIAL's that have a RESULT of "PASS" and plot them for each day. The closest I have managed to get is the following:
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim query As String
Dim FullDatabasePath As String = "C:\db.accdb"
Dim dbProvider As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
Dim dbSource As String = " Data Source = " & FullDatabasePath
Dim table As String = "tblQA"
query = "SELECT [DATE], (SELECT COUNT([SERIAL]) FROM " & table & " WHERE [DATE] BETWEEN #" & dtpFrom.Value.ToString("MM/dd/yyyy") & "# And #" & dtpTo.Value.ToString("MM/dd/yyyy") & "# AND RESULT = 'PASS') as RowCount FROM [" & table & "] WHERE DATE BETWEEN #" & dtpFrom.Value.ToString("MM/dd/yyyy") & "# And #" & dtpTo.Value.ToString("MM/dd/yyyy") & "# AND RESULT = 'PASS'"
Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection
con.ConnectionString = dbProvider & dbSource
da = New OleDb.OleDbDataAdapter(query, con)
ds.Clear()
con.Open()
da.Fill(ds, table)
con.Close()
Chart1.Series.Add("PASS")
Chart1.DataSource = ds.Tables(table)
Chart1.Series("PASS").XValueMember = "DATE"
Chart1.Series("PASS").YValueMembers = "RowCount"
If I select 1/5/2016 for both start and end dates using the DateTimePickers on my form (dtpFrom and dtpTo), my chart shows me 2 serials on 1/5/2016. Likewise, it shows 1 serial if I choose a start and end date of 1/6/2015. (yay)
If choosing a start date of 1/5/2016 and end date of 1/7/2016, it shows 4 serials on each of those 3 days. (boo)
How can I make it not accumulate, but instead display the number of passing serials for each day?

I believe this SQL will do what you want:
SELECT [DATE], COUNT(RESULT)
FROM Table_1
where result = 'PASS' AND [Date] BETWEEN '20160501' AND '20160701'
group by [date]
EDIT: The dates are formatted to suit MS T-SQL - you'll have to tweak these to suit Access ( and your dtp's) of course.

Related

How to find field with date range?

So I'm trying to select record with a specific date range ex. 5/21/2019 - 5/30/2019 and put the records into a datagridview.
I'm using Ms. Access and I don't know many things about SQL.
DA = New OleDb.OleDbDataAdapter("SELECT * FROM table where date >= " & DateValue(FirstDate) & " AND date <= " & DateValue(SecondDate) & "", conn)
DS = New DataSet
DS.Clear()
DA.Fill(DS, "table")
DataGridView1.DataSource = DS.Tables("table")
It doesn't give me an error message, but the datagridview doesn't show anything. Thanks for your response
In MS Access, the date delimiter is a hash (#).
So have to change your query to:
"SELECT * FROM table where date >= #" & DateValue(FirstDate) & "# AND date <= #" & DateValue(SecondDate) & "#"
Or you use the between operator:
"Select * FROM table WHERE [Date] Between #" & DateValue(FirstDate) & "# and #" & DateValue(SecondDate) & "#";
A better way to handle this is to simply use parameters which is commonly recommended by many programmers.
da = New OleDb.OleDbDataAdapter("SELECT * FROM table where date >= #StartDate AND date <= #EndeDate ", conn)
'If you show how you declare and set FirstDate and SecondDate we can drop the DateValue function'
da.SelectCommand.Parameters.Add("#StartDate", OleDb.OleDbType.Date).Value = DateValue(FirstDate)
da.SelectCommand.Parameters.Add("#EndeDate", OleDb.OleDbType.Date).Value = DateValue(SecondDate)
ds = New DataSet
DS.Clear()
DA.Fill(DS, "table")
DataGridView1.DataSource = DS.Tables("table")
SELECT ID
FROMTestInfo
WHERE CapturedDate BETWEEN ‘2012-03-27’ AND ‘2012-03-28 ’

i want to filter my data with this from using visual studio 2015

I want to sort the data in the database with the date as the main condition with 2 date time picker 1 as the starting date and the other as the limit with this code by using between but I do not know the correct query form...my from looks like this the first DTP name is DTPDari and second DTPSampai
Call KONEKSI()
CMD = New OleDbCommand("SELECT * FROM Pembayaran where tanggal_pembayaran BEETWEEN '" & DTPDari.Value & "'AND tanggal_pembayaran = '" & DTPSampai.Value & "'", CONN)
DR = CMD.ExecuteReader
DR.Read()`
From the little what I understand from your question you can use any of the below
(syntax not tested)
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran BETWEEN '" & DTPDari.Value & "' AND '" & DTPSampai.Value & "')
or
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran > '" & DTPDari.Value & "') and (tanggal_pembayaran < '" & DTPSampai.Value & "')
Adding Function sample asper your request
Sub GetDetails()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString.ToString()
Dim connection As New SqlConnection(connectionString)
Dim queryString2 = "SELECT *
FROM dbo.Customers
WHERE (CreationDate BETWEEN #param1 AND #param2)"
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandText = queryString2
cmd.Connection = connection
cmd.Parameters.AddWithValue("#Param1", from_DateTimePicker.Value.Date)
cmd.Parameters.AddWithValue("#param2", to_DateTimePicker.Value.Date)
connection.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
'here fill on datatable Or anything you want
End While
connection.Close()
End Sub

Printing bulk reports in crystal report programmatically using vb.net and sql server

Please I am working on a School management system in vb.net and will like to print all the reports of students in a particular class in bulk at the same time programmatically. What I have done so far is, I select all the students IDs of a particular class from the studentstb which is the master table and fill the DataTable with it. I now iterate through the items using a for loop.
The bulk printing seams to work but the ranking which should have been base on a class is now repeating itself to display multiple subjects for one student.
If the number of subjects the student registered are six, it is repeating the six subjects to display about 18 of the same subjects.
Below is the code I have written:
Public Sub printbulk()
If mysqlconnectionstring.State = ConnectionState.Broken Then
mysqlconnectionstring.Open()
End If
rem instance of the crystal report
Dim rpt As CrystalReportbulkreport = New CrystalReportbulkreport
rem instance of the dataset and dataAdapter to fill the dataset for the crystal report
Dim da As New SqlDataAdapter
Dim da1 As New SqlDataAdapter
Dim ds As New DataSet
Dim dar As New SqlDataAdapter
Dim atten As New SqlDataAdapter
Dim bi As New SqlDataAdapter
Dim b As New SqlDataAdapter
Dim strclass As String = bclasss.Text
Dim strterm As String = termc.Text
Dim sess As String = sessionb.Text
rem open a printer dialogue
Me.PrintDialogbulk.Document = Me.PrintDocumentbulk
Dim dr = Me.PrintDialogbulk.ShowDialog()
if dr = DialogResult.OK then
Dim dt As New DataTable
Dim df As New SqlDataAdapter
Dim strid As String
Dim strget As String = "select studentid from studentstb where stuclass='" & strclass & "'"
df.SelectCommand = New SqlCommand(strget, mysqlconnectionstring)
df.Fill(dt)
rem iterate throuh the dataTable studentid
For Each row As DataRow In dt.Rows
For Each coll As DataColumn In dt.Columns
strid = row("studentid")
rem get the students rank in class plus some other info from assessment table
rem get student position in exam
Dim str1 As String = " SELECT * FROM (SELECT studentid,stuname,session,f_score,stuclass,term,subject,final_ca,final_exam,ca,exam_score,remarks,f_scores = SUM(f_score),position = DENSE_RANK() OVER (ORDER BY SUM(f_score) desc) FROM assessment WHERE stuclass = '" & strclass & "' and term='" & strterm & "' and session='" & sess & "' GROUP BY studentid,f_score,stuclass,term,subject,final_ca,final_exam,ca,exam_score,stuname,session,remarks) T WHERE studentid = '" & strid & "' "
da.SelectCommand = New SqlCommand(str1, mysqlconnectionstring)
rem get student remarks & conduct from the remarks table
Dim strr As String = "select class_attendance,conduct,interest,promoted_to,cremarks from remarks where studentid='" & strid & "' and stuclass='" & strclass & "' and term='" & strterm & "' and session='" & sess & "' "
dar.SelectCommand = New SqlCommand(strr, mysqlconnectionstring)
rem get student pic
Dim str11 As String = "select studentid,photo from studentstb where stuclass='" & strclass & "' and studentid='" & strid & "' "
da1.SelectCommand = New SqlCommand(str11, mysqlconnectionstring)
rem get student attendance
Dim stratten = "select attendance,reopen from attendance1 where term ='" & strterm & "' and session ='" & sess & "' "
atten.SelectCommand = New SqlCommand(stratten, mysqlconnectionstring)
rem get student bill from takehomebill table
Dim h = "select studentid,sum(amt_topay) as amt_topay from takehomebill where class='" & strclass & "' and lodging=(select lodging from studentstb where studentid='" & strid & "') group by studentid "
bi.SelectCommand = New SqlCommand(h, mysqlconnectionstring)
rem fil the datasets with the various dataAdapters
dar.Fill(ds, "remarks")
da.Fill(ds, "assessment")
da1.Fill(ds, "studentstb")
atten.Fill(ds, "attendance1")
bi.Fill(ds, "takehomebill")
rem Assign the print to the crystap report
rpt.SetDataSource(ds)
rpt.SetParameterValue("c1", strclass)
rpt.SetParameterValue("c2", strid)
rpt.PrintToPrinter(1, False, 0, 0)
Next
Next
end if
mysqlconnectionstring.Close()
End Sub
I was able to solve it by inserting a group into the crystal report. I used the studentid as the group name. I checked insert new page after the group footer.
Thank you.

select records which will be ended after 2 days

I need to get the records that will be ended after two days
but always I got an empty datagridview.
I have tried this code:
Dim after2days As Date = Today.Date.AddDays(3)
Dim sqlstr As String = "SELECT * FROM tblvac where vend between " & Today.Date & " and " & after2days & " "
Dim da As New OleDbDataAdapter(sqlstr, Conn)
ds.Reset()
da = New OleDbDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Conn.Close()
Why is this happening and how can I fix it?
Access SQL includes functions, Date() and DateAdd(), which can give you the date range you want for your query.
Dim sqlstr As String = "SELECT * FROM tblvac where vend between Date() and DateAdd('d', 3, Date());"
If you prefer to pass date values from your VB.Net code to the db engine, use a parameter query so that you needn't bother about date format and delimiters. Just supply valid Date/Time values for the parameters.
You are building your query as a string and thus need to use the convert to date function... for MS Access its DateValue see http://www.techonthenet.com/access/functions/date/datevalue.php
Try
Dim sqlstr As String = "SELECT * FROM tblvac where vend between
DateValue('" & Today.Date & "') and DateValue('" & after2days & "') "
As commented by HansUp... this solution needs to have the date format as mm/dd/yyyy or yyyy-mm-dd

multiple parameter selection in crystal report in .net not working

Form contains 1 texbox to hold Student ID and two Date-time Picker to select fees paid month by student and i am able to select date range of all students , where unable to filter fromdate to Todate with particular one Student.
i am getting error ....Please Help....... here is my problem code
Dim dbCommand As New OleDb.OleDbCommand
Dim myreport As New CrystalReport2
Dim Dt As New DataTable
Dim da As New OleDb.OleDbDataAdapter
dbCommand.CommandText = "Select FeesMonth between #" & FromDate.Text & "# and #" & ToDate.Text & "# From StudentPayments Where StudentID= '" & TextBox1.Text & "'"
da.SelectCommand = dbCommand
da.Fill(Dt)
myreport.SetDataSource(Dt)
CrystalReportViewer1.ReportSource = myreport
CrystalReportViewer1.Show
you have to give Connectionstring to dbCommand.
like -
OleDbConnection con=new OleDbConnection ();
dbCommand.Connectionstring=con;