CSQL code in vb6 for displaying data between two dates? - sql

Set COUNTER_RS = New Recordset
COUNTER_RS.Open "Select * from TT_COUNTER where Trans_dt >'" + Format(mskFdate.Text, "mm-dd-yyyy") + "' and Trans_dt <='" + Format(mskTdate.Text, "mm-dd-yyyy") + "' and Receipt_No like 'A%' and Head_Details='MED' order by Receipt_No", db, adOpenStatic, adLockOptimistic
MEDI = 0
If COUNTER_RS.RecordCount > 0 Then
While COUNTER_RS.EOF = False
MEDI = Val(COUNTER_RS!Rate)
COUNTER_RS.MoveNext
Wend
End If
Cant find the correct amount between two dates, please help with the code?

Related

(Ms Access) Row_Number() Over Partition

How can I convert the row_number() function with an over partition on MS ACCESS? What I want to achieve is:
from this table:
ID | EntryDate
10 | 2016-10-10
10 | 2016-12-10
10 | 2016-12-31
10 | 2017-01-31
10 | 2017-03-31
11 | 2015-01-31
11 | 2017-01-31
To this output, showing only the top 3 latest of each ID:
ID | EntryDate
10 | 2016-12-31
10 | 2017-01-31
10 | 2017-03-31
11 | 2015-01-31
11 | 2017-01-31
On SQL Server, i can achieved this using the following code:
select T.[ID],
T.[AptEndDate],
from (
select T.[ID],
T.[AptEndDate],
row_number() over(partition by T.[ID] order by T.[AptEndDate] desc) as rn
from Table1 as T
) as T
where T.rn <= 3;
Consider a count correlated subquery which can work in any RDBMS.
select T.[ID], T.[EntryDate]
from
(select sub.[ID],
sub.[EntryDate],
(select count(*) from Table1 c
where c.ID = sub.ID
and c.[EntryDate] >= sub.[EntryDate]) as rn
from Table1 as sub
) as T
where T.rn <= 3;
It might be simpler and faster to use Top n - as you mention yourself:
Select T.[ID], T.[EntryDate]
From Table1 As T
Where T.[EntryDate] In
(Select Top 3 S.[EntryDate]
From Table1 As S
Where S.[ID] = T.[ID]
Order By S.[EntryDate] Desc)
Order By T.[ID] Asc, T.[EntryDate] Asc
Anything using the OVER clause is something known as a Windowing Function. Unfortunately, MS Access does not have support for Windowing Functions.The easiest solution in this case may be to back to VBA code :(
Public Const tableName As String = "[TransactionalData$]"
Public Const parentId As String = "parentId"
Public Const elementId As String = "Id"
Public Const informationalField As String = "Label"
Sub TransactionalQuery(Optional ByVal Id As Integer = 0)
Dim rs As New ADODB.Recordset, cn As New ADODB.Connection
Dim sqlString As String
''' setup the connection to the current Worksheet --- this can be changed as needed for a different data source, this example is for EXCEL Worksheet
cn.Open ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties='Excel 12.0 Macro;HDR=YES;IMEX=1'")
'''' Alternate method for the query
sqlString = "SELECT ParentId, Rank() OVER(PARTITION BY ParentId ORDER BY Label) , vlu.Id, vlu.Label FROM [TransactionalData$] var LEFT JOIN [TransactionalData$] vlu ON vlu.Id=var.ParentId"
''' will need to change the TableName (TransactionalData$]
sqlString = "SELECT DISTINCT " & elementId & " FROM " & tableName & " WHERE " & parentId & " = " & Id
rs.Open sqlString, cn, adOpenStatic, adLockReadOnly
'' Start collecting the SQL UNIONs to run at the end
sqlString = ""
Do While Not rs.EOF
'' Add current Element to the UNION
sqlString = sqlString & "SELECT * FROM " & tableName & " WHERE " & elementId & " = " & rs.Fields(elementId) & " UNION " & vbCrLf
'' Add all children element to the UNION
sqlString = sqlString & subQuery(cn, rs.Fields(elementId))
rs.MoveNext
Loop
rs.Close
'''Debug.Print sqlString
''' Remove the extra UNION keyword at the end
sqlString = Left(sqlString, Len(sqlString) - 8)
''' Exectue the built query
rs.Open sqlString, cn, adOpenStatic, adLockReadOnly
''Do While Not rs.EOF
'' Debug.Print rs.Fields(elementId) & ", " & rs.Fields(informationalField)
'' rs.MoveNext
''Loop
End Sub
Function subQuery(cn As ADODB.Connection, Id As Integer) As String
Dim sqlString As String
Dim subSqlString As String, rs As New ADODB.Recordset
'' Create a list of children for the current element
sqlString = "SELECT DISTINCT " & elementId & " FROM " & tableName & " WHERE " & parentId & " = " & Id
rs.Open sqlString, cn, adOpenStatic, adLockReadOnly
'' start the SQL for current elements children
sqlString = ""
Do While Not rs.EOF
''' add in the current element to the UNION
sqlString = sqlString & "SELECT * FROM " & tableName & " WHERE Id = " & rs.Fields(elementId) & " UNION " & vbCrLf
''' recursively find additional children for the current element
sqlString = sqlString & subQuery(cn, rs.Fields(elementId))
rs.MoveNext
Loop
rs.Close
''' return the SQL for the current element and all its children
subQuery = sqlString
End Function

String Constant must End with double quote SQL report

Below is the query for a sql report that I am completing in SQL Server Business Studio and I keep getting an error regarding the double quotes on this line Dim SelectClause as System.String = ""
I tried a few things but I get the repeating error.
Any help would be appreciated.
Function getSelectClause(ByVal startDate as DateTime, ByVal endDate as DateTime) as String
Dim SelectClause as System.String = ""
SelectClause ="SELECT Define.meterName, SUM(Reading.volume) AS [Total Volume], MIN(Reading.time) AS [Month]
FROM [Reading] INNER JOIN Define ON Reading.meterId = Define.meterId
WHERE (Reading.[time] >= " & startDate & " AND Reading.[time]< " & endDate & ")
AND Define.meterName IN ('007080')
AND (Reading.dataQuality = '11' OR
Reading.dataQuality = '10') AND (Reading.auditVersion = '0')
GROUP BY Define.meterName"
return SelectClause
End Function
SSRS uses VB as its language for custom functions, which has a different syntax that SQL. VB does not support multi-line statements like SQL does. You need to end each line with " + _ and begin the continuation with ", and change how you append the date strings :
Function getSelectClause(ByVal startDate as DateTime, ByVal endDate as DateTime) as String
Dim SelectClause as System.String = ""
SelectClause ="SELECT Define.meterName, SUM(Reading.volume) AS [Total Volume], " + _
" MIN(Reading.time) AS [Month]" + _
" FROM [Reading] INNER JOIN Define ON Reading.meterId = Define.meterId" + _
" WHERE (Reading.[time] >= '" + startDate + "' AND Reading.[time]< '" + endDate+ "')" + _
" AND Define.meterName IN ('007080')" + _
" AND (Reading.dataQuality = '11' OR " + _
" Reading.dataQuality = '10') AND (Reading.auditVersion = '0') " + _
" GROUP BY Define.meterName"
return SelectClause

SQL Syntax error, expression of non-boolean type

This code is supposed to create a graph of revenue from money made through sales tickets at an event.
The code only executes up to da.Fill(ds) when it returns the error, which can be seen at the end of the code.
Does anybody know why
Private Sub frmRevenue_Load(sender As Object, e As EventArgs) Handles Me.Load
frmMDI.addFormToCMS()
Dim dt As DataTable
dt = New DataTable
dt.Columns.Add("Fee")
Dim sales As Integer = 0
Dim gridtable As New DataTable
gridtable.Columns.Add("Month")
gridtable.Columns.Add("Total")
gridtable.Columns.Add("#")
For i = 1 To 12
sql = "SELECT Fee FROM tblTickets WHERE MONTH(DatePurchased) = " & i & " AND (YEAR(DatePurchased) = " & Today.Year & " OR " & Year(Today.AddYears(1)) & ") AND (Status = 'SOLD' OR RESERVED" _
& " = 'AWAITING CONFIRMATION' OR Status = 'AVAILABLE' OR Status = 'AWAITING PAYMENT');"
da = New OleDb.OleDbDataAdapter(sql, con)
ds = New DataSet
da.Fill(ds)
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
monthly(i) = monthly(i) + 1
contracts = sales + 1
total(i) = total(i) + dr.Item("Fee")
yearlytotal = yearlytotal + dr.Item("Fee")
Next
Next
For i = 1 To 12
Dim month As String
Select Case i
Case 1
month = "Jan"
Case 2
month = "Feb"
Case 3
month = "Mar"
Case 4
month = "Apr"
Case 5
month = "May"
Case 6
month = "Jun"
Case 7
month = "Jul"
Case 8
month = "Aug"
Case 9
month = "Sep"
Case 10
month = "Oct"
Case 11
month = "Nov"
Case 12
month = "Dec"
Case Else
month = "ERR"
End Select
gridtable.Rows.Add(month, FormatCurrency(total(i)), monthly(i))
Next
ugTickets.DataSource = gridtable
ugTickets.DisplayLayout.Bands(0).Columns("Month").Width = 35
ugTickets.DisplayLayout.Bands(0).Columns("#").Width = 20
ugTickets.DisplayLayout.Override.AllowUpdate = DefaultableBoolean.False
txtAnnual.ReadOnly = True
txtAnnual.BackColor = Color.White
txtAnnualContracts.ReadOnly = True
txtAnnualContracts.BackColor = Color.White
chRevenue.Titles("chTitle").Text = "Predicted revenue for " & Today.Year & " - " & Year(Today.AddYears(1))
txtAnnual.Text = FormatCurrency(yearlytotal, 2)
txtAnnualContracts.Text = contracts
chRevenue.Series("Series1").Name = "Revenue"
For i = 1 To 12
chRevenue.Series("Revenue").Points.AddY(total(i))
Next
Try
chRevenue.BackColor = Color.Transparent
chRevenue.Legends("Revenue").BackColor = Color.Transparent
chRevenue.Series("Revenue").ChartArea = "ChartArea1"
chRevenue.Series("Revenue").Color = Color.SkyBlue
chRevenue.Series("Revenue").ToolTip = FormatCurrency("#VALY", 2)
Catch
End Try
End Sub
An expression of non-boolean type specified in a context where a condition is expected, near ')'.
The problem is with this bit of the SQL:
(YEAR(DatePurchased) = " & Today.Year & " OR " & Year(Today.AddYears(1)) & ")
It should probably be
(YEAR(DatePurchased) = " & Today.Year & " OR YEAR(DatePurchased) = " & Year(Today.AddYears(1)) & ")
The OR in SQL (and in most other languages) needs to have two independently valid conditions on each side. The left hand side currently looks like this:
YEAR(DatePurchased) = 2016
...which is fine. But the right looks like this:
2017
...which isn't a valid boolean.
When you get an error like this on the da.Fill() line (ie. the line that's actually running the SQL in the database), the easiest way to debug it is to print out the value of the "sql" variable.
Often, you can just look at the SQL it's generated and the problem will be obvious. Other times you have to copy it and run it directly against your database to see what the problem is.
Might be your SQL, try:
"SELECT Fee FROM tblTickets WHERE MONTH(DatePurchased) = '" & i &
"' AND (YEAR(DatePurchased) = '" & Today.Year &
"' OR '" & Year(Today.AddYears(1)) & "') " &
"AND (Status = 'SOLD' OR RESERVED = 'AWAITING CONFIRMATION' " &
"OR Status = 'AVAILABLE' " &
"OR Status = 'AWAITING PAYMENT');"

get data after union max and min sql statement

Is there any way to combine these sql statements in one statement:
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()
the table att has data as:
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
i was trying since morning and didn't come up with something, the problem that when i union the 2 sql statement i couldn't get the "byu" of MAX(atttime) and also the "byu" of MIN(atttime) via SqlDataReader. I almost red all the questions in the site that related to this and nothing worked for me so far.the result of above code is:
2 2015/01/02 07:05:02 0
2 2015/01/02 19:15:02 1
please help, thanks.
You can join you queries like this and execute them as a batch statement
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 ;"
This is the only idea i dont know how many columns you are getting from database you have to set your cells() value respective of column order which you are getting from database
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

How to merge cells and remove blank spaces in my DataGrid using proper loop

My title is still broad so i'll explain here further.
This is my current output using my code:
.
But I want to make it look like this..
As you can see on the pictures, i want to remove the blank spaces. Because if I selected MORE data, let's say I selected 7 more days, it will go DIAGONALLY not horizontally.
I think I have a problem regarding my loops. Hope you can help me trace because I've been stuck here for a week debugging. (nevermind my long query, i just want to post all my code. I've also added comments for easier debugging.)
Here's my code:
Private Sub LoadDateAndUser()
Dim SqlStr As String = ""
Dim sqlConn As New SqlConnection(DataSource.ConnectionString)
Dim sqlComm As New SqlCommand(SqlStr, sqlConn)
Dim sqlAdapter As New SqlDataAdapter(sqlComm)
Dim o_Dataset As New DataSet()
SqlStr = " SELECT convert(varchar(10), A.TransDate, 101) as TransDate,ADMMED.TransNum, ADMMED.AdministeredDate, D.Dosage [Dosage], ISNULL(C.GenericName, ' ') + ' (' + IsNull(B.ItemName,'') + ' ' + IsNull(B.ItemDesc,'') + ')' [Medication], ADMMED.UserID" & _
" FROM INVENTORY..tbInvStockCard as A" & _
" LEFT OUTER JOIN INVENTORY..tbInvMaster as B On A.ItemID = B.ItemID " & _
" LEFT OUTER JOIN Inventory.dbo.tbForGeneric as C On B.GenericID = C.GenericID" & _
" LEFT OUTER JOIN Station..tbNurse_AdministeredMedicines ADMMED on a.idnum= ADMMED.idnum " & _
" LEFT OUTER JOIN build_file.dbo.tbCoDosage as D on A.DosageID = D.DosageID" & _
" LEFT OUTER JOIN Station.dbo.tbNurseCommunicationFile as E on A.IdNum = E.IDnum and E.ReferenceNum = A.RefNum" & _
" WHERE A.IdNum = '" & Session.Item("IDNum") & "' and ( A.RevenueID = 'PH' or A.RevenueID = 'PC' ) " & _
" AND A.LocationID = '20' and Not IsNull(ADMMED.AdministeredDate, '') = ''" & _
" AND A.RefNum = ADMMED.ReferenceNum and ADMMED.ItemID = A.itemid" & _
" AND (B.ItemClassificationID = '1' or B.ItemClassificationID = '10' or B.ItemClassificationID = '11' or B.ItemClassificationID = '16' or B.ItemClassificationID = '2' or B.ItemClassificationID = '9')" & _
" order by TransDate desc,ADMMED.AdministeredDate desc"
sqlComm.CommandText = SqlStr
sqlAdapter.Fill(o_Dataset, "Table")
Dim o_Row As DataRow
Dim o_AdmDates As New Collection()
Dim s_FormattedLastAdmDate As String = ""
Dim s_FormattedAdmDate As String = ""
Dim o_DerivedTable As New DataTable()
With o_DerivedTable
.Columns.Add("TransDate")
.Columns.Add("Medication")
.Columns.Add("Dosage")
.Columns.Add("TransNum")
End With
'Select all unformatted administered dates from the query
Dim o_UnformattedAdmDates As DataRow() = o_Dataset.Tables(0).Select("", "AdministeredDate Desc")
'Extract distinct administered dates and change its format
For Each o_Row In o_UnformattedAdmDates
s_FormattedAdmDate = Format(CDate(o_Row.Item("AdministeredDate")), KC_Date_Format) 'eg. Jan 01 15
If s_FormattedLastAdmDate <> s_FormattedAdmDate Then
s_FormattedLastAdmDate = s_FormattedAdmDate
o_AdmDates.Add(s_FormattedLastAdmDate) 'add all formatted dates in o_AdmDates
End If
Next
'Add formatted administred dates to derived table
Dim o_Item As String
For Each o_Item In o_AdmDates
o_DerivedTable.Columns.Add(o_Item)
Next
'Loop through the administred date
Dim o_NewRow As DataRow
Dim o_NextRow As DataRow
Dim i_Ctr As Integer
Dim x_isNewRow As Boolean = True
Dim i_MaxRec As Integer
i_MaxRec = o_Dataset.Tables(0).Rows.Count - 1
For i_Ctr = 0 To i_MaxRec
o_Row = o_Dataset.Tables(0).Rows(i_Ctr)
If i_Ctr <> i_MaxRec Then
o_NextRow = o_Dataset.Tables(0).Rows(i_Ctr + 1)
End If
If x_isNewRow Then
o_NewRow = o_DerivedTable.NewRow()
End If
o_NewRow("TransDate") = o_Row("TransDate")
o_NewRow("Medication") = o_Row("Medication")
o_NewRow("Dosage") = o_Row("Dosage")
o_NewRow("TransNum") = o_Row("TransNum")
'Fill approriate result date column based on query
For Each o_Item In o_AdmDates
s_FormattedAdmDate = Format(CDate(o_Row.Item("AdministeredDate")), KC_Date_Format)
Dim AdmTim As DateTime = DateTime.Parse(o_Row("AdministeredDate"))
If s_FormattedAdmDate = o_Item Then
o_NewRow(s_FormattedAdmDate) = AdmTim.ToString("hh:mm tt") + " - " + o_Row("UserID")
End If
Next
If i_Ctr < i_MaxRec _
And Not o_NextRow Is Nothing _
And o_Row("TransDate") = o_NextRow("TransDate") _
And o_Row("Medication") = o_NextRow("Medication") _
And o_Row("Dosage") = o_NextRow("Dosage") _
And o_Row("AdministeredDate") = o_NextRow("AdministeredDate") Then
x_isNewRow = False
Else
o_DerivedTable.Rows.Add(o_NewRow)
x_isNewRow = True
End If
Next
'Bind derived table
dgSheet.DataSource = o_DerivedTable
dgSheet.DataBind()
If o_Dataset.Tables(0).Rows.Count > 0 Then
GroupGridView(dgSheet.Items, 0, 3)
Else
End If
End Sub
I think you must review your programming logic:
After that huge ugly SqlStr : you will have a DataSet, with a Table with all rows mixed !?
Let's try a pseudo-code:
I think is better to create in that DataSet, 2 Tables:<br>
**first** table with: id, DateOrder, Medication, Dosage <br>
and **second** table with: idDate, FirstTable.id, AdministeredDate
after that you know how many ADMMED.AdministeredDate.Count are, because you must know how manny columns you need to add
create a 3-rd table from iteration of first table, nested with second by ID.
Set as Datasource for DataGridView the Third DataTable.
So you have 2 datasets, and generate this one .. one to many ..
.. I have no time now, if you don't get the ideea .. forget it !