how to display columns in specific order, according to field value in MS Access - sql

I want to display a query but the column order needs to be sorted according to the value in the column, field with greater value as column 1, then second greater value field as column 2, and so on. The query will only produce one row as it shows data for the current month. I know I could do this in VBA, with a bubble sort or something, and build the SQL query accordingly, but I was wondering if there was a quicker way to do this. Data is like this: DataMonth, Data1, Data2, Data3,... all the way to Data8. Please don't mention data structure is bad, as I am only trying to help someone here, and it is a bit too late to rebuild their tables structures...

No need to sort in the VBA. First get a record set that lists the columns in the right order with the Column Name as one of the columns - order that query by the value in each column. I used a query that got each single column with UNION e.g. here is my entire module
Option Compare Database
Option Explicit
Private Sub ReorderColumns()
Dim mnth As Integer
mnth = 1 'CHANGE MONTH
Dim qry As String
Dim rs As DAO.Recordset
qry = GetSQL(mnth)
Set rs = CurrentDb.OpenRecordset(qry)
Dim i As Integer: i = 0 'Count of columns added to query
qry = "SELECT "
While Not rs.EOF
i = i + 1
qry = qry & rs.Fields("ColName") & IIf(i < 8, ",", "")
rs.MoveNext
Wend
qry = qry & " FROM Table1 WHERE DataMonth = %s"
qry = stuffStr(qry, mnth)
rs.Close
'Get the results in the order you need
Set rs = CurrentDb.OpenRecordset(qry)
'Do something with the data here
rs.Close
Set rs = Nothing
End Sub
Public Function GetSQL(mnth As Integer) As String
Dim outp As String
outp = "SELECT 'Data1' as ColName, Data1 as DataValue FROM Table1 WHERE DataMonth = %s UNION ALL " & _
"SELECT 'Data2' as ColName, Data2 as DataValue FROM Table1 WHERE DataMonth = %s UNION ALL " & _
"SELECT 'Data3' as ColName, Data3 as DataValue FROM Table1 WHERE DataMonth = %s UNION ALL " & _
"SELECT 'Data4' as ColName, Data4 as DataValue FROM Table1 WHERE DataMonth = %s UNION ALL " & _
"SELECT 'Data5' as ColName, Data5 as DataValue FROM Table1 WHERE DataMonth = %s UNION ALL " & _
"SELECT 'Data6' as ColName, Data6 as DataValue FROM Table1 WHERE DataMonth = %s UNION ALL " & _
"SELECT 'Data7' as ColName, Data7 as DataValue FROM Table1 WHERE DataMonth = %s UNION ALL " & _
"SELECT 'Data8' as ColName, Data8 as DataValue FROM Table1 WHERE DataMonth = %s ORDER BY 2"
GetSQL = stuffStr(outp, mnth, mnth, mnth, mnth, mnth, mnth, mnth, mnth)
End Function
Function stuffStr(str As String, ParamArray subs()) As String
Dim i As Long
Dim outp As String
outp = str
For i = 0 To UBound(subs)
outp = Replace(Expression:=outp, Find:="%s", Replace:=subs(i), Count:=1, Compare:=vbTextCompare)
Next
stuffStr = outp
End Function
Not the most efficient way because of all the string manipulation, but it works

Related

MS Access VBA multiple list box search form

I have a requirement to allow a user to search between two dates on a form and filter the data down further using multiple list boxes
Currently I allow the user to search between a from and to date... And also filter by products from a listbox.
If no products are selected in the list box, only display the results of the query between the two dates.
If the selection critera of the listbox is not empty, build the query WHERE with IN clause and then concanenate it to the SELECT statement, then execute the query to give desired results.
My question is... How would I do this for another four or five multi value list boxes? For example: Suppliers, Depots, Countries, Varieties etc etc
SearchAllReject is simply a function to query from and to date with no product filters.
Here is the code I already have:
Dim SQLAllReject As String
Dim strDateFrom As String
Dim strDateTo As String
Dim strFirstDate As Date
Dim strSecondDate As Date
Dim strINPRODUCT As String
Dim strWHERE As String
Dim strSTRING As String
Dim i As Integer
If Len(Me.txtDate.Value & vbNullString) = 0 Then
MsgBox ("Please input date from")
Exit Sub
ElseIf Len(Me.txtDateTo.Value & vbNullString) = 0 Then
MsgBox ("Please input date to")
Exit Sub
End If
strDateFrom = txtDate.Value
strDateTo = txtDateTo.Value
strFirstDate = Format(CDate(strDateFrom), "mm/dd/yyyy")
strSecondDate = Format(CDate(strDateTo), "mm/dd/yyyy")
For i = 0 To lstProduct.ListCount - 1
If lstProduct.Selected(i) Then
strINPRODUCT = strINPRODUCT & "'" & lstProduct.Column(1, i) & "',"
End If
Next i
If Len(strINPRODUCT & vbNullString) = 0 Then
SearchAllReject
Else
strWHEREPRODUCT = "AND dbo_busobj_file_rejections_load_temp5.Tesco_Product_Name IN " & _
"(" & Left(strINPRODUCT, Len(strINPRODUCT) - 1) & "))"
SQLAllReject = "SELECT dbo_busobj_file_rejections_load_temp5.Reject_Date AS [Date], " & _
"dbo_busobj_file_rejections_load_temp5.Depot_Number AS [Depot No], " & _
"dbo_busobj_file_rejections_load_temp5.Depot_Name AS [Depot], dbo_busobj_file_rejections_load_temp5.Tesco_Product_Name AS [Product]," & _
"dbo_busobj_file_rejections_load_temp5.Tesco_Brand_Name AS [Brand], dbo_busobj_file_rejections_load_temp5.Tesco_Packsize AS [Packsize], " & _
"dbo_busobj_file_rejections_load_temp5.TPNB, dbo_busobj_file_rejections_load_temp5.EAN, " & _
"dbo_busobj_file_rejections_load_temp5.Tesco_Country_of_Origin AS [Country], " & _
"dbo_busobj_file_rejections_load_temp5.Tesco_Variety AS [Variety], dbo_busobj_file_rejections_load_temp5.Tesco_Producer AS [Producer], " & _
"dbo_busobj_file_rejections_load_temp5.reject_qty AS [Quantity], dbo_busobj_file_rejections_load_temp5.batch_code AS [Batch Code], " & _
"dbo_busobj_file_rejections_load_temp5.site AS [Site], dbo_busobj_file_rejections_load_temp5.Tesco_Comment AS [Comment], " & _
"dbo_busobj_file_rejections_load_temp5.Tesco_Reason AS [Reason] " & _
"FROM dbo_busobj_file_rejections_load_temp5 " & _
"WHERE (((dbo_busobj_file_rejections_load_temp5.Reject_Date) Between #" & strFirstDate & "# And #" & strSecondDate & "#) "
strSTRING = SQLAllReject & strWHEREPRODUCT
Debug.Print strSTRING
Me.lstDeleteReject.RowSource = strSTRING
Me.lstDeleteReject.Requery
Consider building an entity-attribute table of all possible listbox values and use a saved SQL query which avoids any messy concatenation of SQL in VBA. A parameterized query using QueryDef is used to update the selected options of table of all list box values.
Table (myListBoxValues) (built once and updated with new values/categories)
Category|Value |Selected
--------|----------|--------
Product |Product A | 1
Product |Product B | 1
Product |Product C | 1
...
Country |USA | 1
Country |Canada | 1
Country |Japan | 1
Above can be populated with multiple append queries using SELECT DISTINCT:
INSERT INTO myListBoxValues ([Category], [Value], [Selected])
SELECT DISTINCT 'Product', Tesco_Product_Name, 1
FROM dbo_busobj_file_rejections_load_temp5 b
NOTE: It is very important to default all Selected to 1 for VBA purposes. See further below. Also, if you have a mix of number and string, consider using TextValue and NumberValue columns and adjust in SQL IN clauses. Save above query as a new object and place the named object behind target: lstDeleteReject.
SQL (built once, adjust form name)
Notice the form date values are directly incorporated into WHERE clause without any date formatting conversion or concatenation needs. Also, table alias is used to avoid long name repetition.
SELECT b.Reject_Date AS [Date],
b.Depot_Number AS [Depot No],
b.Depot_Name AS [Depot], b.Tesco_Product_Name AS [Product],
b.Tesco_Brand_Name AS [Brand], b.Tesco_Packsize AS [Packsize],
b.TPNB, b.EAN,
b.Tesco_Country_of_Origin AS [Country],
b.Tesco_Variety AS [Variety], b.Tesco_Producer AS [Producer],
b.reject_qty AS [Quantity], b.batch_code AS [Batch Code],
b.site AS [Site], b.Tesco_Comment AS [Comment],
b.Tesco_Reason AS [Reason]
FROM dbo_busobj_file_rejections_load_temp5 AS b
WHERE b.Reject_Date BETWEEN Forms!myFormName!txtDate
AND Forms!myFormName!txtDateTo
AND b.Tesco_Product_Name IN (
SELECT [Value] FROM myListBoxValues
WHERE [Category] = 'Product' AND [Selected] = 1
)
AND b.site IN (
SELECT [Value] FROM myListBoxValues
WHERE [Category] = 'Site' AND [Selected] = 1
)
AND b.Tesco_Producer IN (
SELECT [Value] FROM myListBoxValues
WHERE [Category] = 'Producer' AND [Selected] = 1
)
AND b.Depot_Name IN (
SELECT [Value] FROM myListBoxValues
WHERE [Category] = 'Depot' AND [Selected] = 1
)
AND b.Tesco_Country_of_Origin IN (
SELECT [Value] FROM myListBoxValues
WHERE [Category] = 'Country' AND [Selected] = 1
)
VBA (adjust list box names to actuals)
Dim qdef As QueryDef
Dim lstname As Variant
Dim sql As String
Dim i As Integer
sql = "PARAMETERS paramValue TEXT, paramCateg INTEGER; " _
& "UPDATE myListBoxes SET [Selected] = 0 " _
& "WHERE [Value] = paramValue AND [Category] = paramCateg"
Set qdef = CurrentDb.CreateQueryDef("", sql)
' ITERATE THROUGH ALL LISTBOXES BY NAME
For Each lstname in Array("lstProduct", "lstSite", "lstProducer", "lstDepot", "lstCountry")
For i = 0 To Me.Controls(lstname).ListCount - 1
' UPDATE IF AT LEAST ONE ITEM IS SELECTED
If Me.Controls(lstname).ItemsSelected.Count > 0
' UPDATE [SELECTED] COLUMN TO ZERO IF VALUES ARE NOT SELECTED
If Me.Controls(lstname).Selected(i) = False Then
qdef!paramValue = Me.Controls(lstname).Value
qdef!paramCategory = Replace(lstName, "lst", "")
qdef.Execute
End If
End If
Next i
Next lstname
Set qdef = Nothing
' REQUERY LISTBOX
Me.lstDeleteReject.Requery
' RESET ALL SELECTED BACK TO 1
CurrentDb.Execute "UPDATE myListBoxValues SET [Selected] = 1"
As you can see, much better readability and maintainability. Also, if users do not select any option, the date range filters are still applied and using your universal table of all list box values, all values will be selected to returns all non-NULL values.

Dynamic Calculated Field in VBA Access

I'm trying to add a field into an existing table. The field is calculated using two variables 'myPrice', which is the price of a record at a certain date, and 'previousPrice', which is the price of the same part from the first record, only a from the month previous. I'm using a loop to iterate through the entire recordset of prices, thereby altering the two variables each time. My code is as follows:
Function priceDifference()
Dim currentPrice As Currency
Dim previousPrice As Currency
Dim recordDate As Date
Dim previousDate As Date
Dim dbsASSP As DAO.Database
Dim priceTable As DAO.TableDef
Dim diffFld As DAO.Field2
Dim rstCurrentPrice As DAO.Recordset
Dim rstPreviousPrice As DAO.Recordset
Dim PN As String
Set dbsASSP = CurrentDb
strSQL = "SELECT * FROM qryPrice"
Set rstCurrentPrice = dbsASSP.OpenRecordset(strSQL, dbOpenDynaset)
Set priceTable = dbsASSP.TableDefs("tblPrice")
Set diffFld = priceTable.CreateField("Difference", dbCurrency)
If Not (rstCurrentPrice.EOF) Then
rstCurrentPrice.MoveFirst
Do Until rstCurrentPrice.EOF = True
PN = rstCurrentPrice![P/N]
recordDate = rstCurrentPrice![myDate]
previousDate = Format(DateAdd("m", -1, recordDate), "M 1 YYYY")
myPrice = rstCurrentPrice!Price
strPreviousSQL = "SELECT * FROM qryPrice WHERE [MyDate] = #" & previousDate & "# AND [Type] = 'Net Price' AND [P/N] = " & PN & ""
Set rstPreviousPrice = dbsASSP.OpenRecordset(strPreviousSQL, dbOpenDynaset)
myCodeName = rstCurrentPrice!CodeName
If DCount("[P/N]", "qryPrice", "[MyDate] = #" & previousDate & "# And [P/N] = " & PN) <> 0 Then
previousPrice = rstPreviousPrice!Price
Else
previousPrice = myPrice
End If
rstCurrentPrice.MoveNext
Loop
Else
MsgBox "Finished looping through records."
End If
diffFld.Expression = myPrice - previousPrice
rstCurrentPrice.Close
rstPreviousPrice.Close
priceTable.Fields.Append diffFld
End Function
Syntactically, it works. The calculated field, however, does not give me the correct values and I cannot figure out why, although I imagine it has something to do with the dynamic formula.
Any help is appreciated. Thanks!!
Your code can't work as you append a number to the field instead of a formula, but you should avoid calculated fields
Use a query:
SELECT
nPrice.[P/N],
nPrice.Price,
nPrice.MyDate,
oPrice.MyDate,
nPrice.Price-Nz(oPrice.Price,nPrice.Price) AS diff
FROM (
SELECT
[P/N],
Price,
MyDate,
Format(DateAdd("m",-1,MyDate),"yyyymm") as previousMonthYear
FROM
tblPrice) AS nPrice
LEFT JOIN (
SELECT
[P/N],
Price,
MyDate,
Format(MyDate,"yyyymm") AS monthYear
FROM
tblPrice) AS oPrice
ON
nPrice.[P/N] = oPrice.[P/N]
AND nPrice.previousMonthYear = oPrice.monthYear
This calculates the difference dynamic and you don't need to store it.
I assume there is max one price per month, otherwise you need to filter the subqueries or just calculate the difference to the last price before.
If the query is too slow ([P/N] and MyDate need an index) , you can still use it to update a field the table tblPrice, but this has to be updated every time a price is updated or inserted in tblPrice
I think you can avoid your code loop by using this query
SELECT A.qryPrice, A.MyDate, B.qryPrice, B.MyDate
FROM qryPrice A LEFT OUTER JOIN qryPrice B
ON A.[P/N] = B.[P/N]
AND B.MyDate = DATEADD(month, -1, A.MyDate)

(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

VB.Net Linq with datatables - select from one table what does not exist in the other

I have two data on which I have applied the linq to select some lines :
csql = "select * from V_Vente where code_projet=" & ComProjet.GetColumnValue("code_projet") & " "
Dim tabVnt as Datatable = utilitaire.getDatatable(csql)
Dim query1 = tabVnt.AsEnumerable().Where(Function(r) DirectCast(r("date"), Date) >= dtDu And DirectCast(r("date"), Date) <= dtAu)
Dim tabAnnule As DataTable = utilitaire.getDatatable("select * from V_Reserv_Annule")
Dim query2 = From cust In tabAnnule.AsEnumerable() Where (cust.type = "définitif" Or cust.type = "Transfert") And cust.date_annule <= dtAu
now what i want is to select rows from "query1" where "Num_R" not exist in "query2".
The column "Num_r" exist in both datatable "tabVnt" and "tabAnnule"
I've tried this code but he doesn't work,please help me to find the error :
dim rows = from t1 in query1 .AsEnumerable() join t2 in query2.AsEnumerable() on t1.Field(Of String)("Num_r") equals t2.Field(Of String)("Num_r") Into tg
From tcheck In tg.DefaultIfEmpty()
Where tcheck = null
Select t1()
If I have understood your code right, you can check if second table's Num_rs does not contain the table one Num_r:
Dim rows = t1.Where(x=> !t2.Select(y=> y.Num_r).Contains(x.Num_r));
I have find the solution for my issus ,and i'd like to share it here with you :
Dim csql = "select * from V_Vente where code_projet=" & ComProjet.GetColumnValue("code_projet") & " "
Dim tabVnt As DataTable = utilitaire.getDatatable(csql)
Dim query1 = tabVnt.AsEnumerable().Where(Function(r) DirectCast(r("date"), Date) >= dt1 And DirectCast(r("date"), Date) <= dt2).ToList
Dim tabAnnule As DataTable = utilitaire.getDatatable("select * from V_Reserv_Annule")
bannedCCList = From c In tabAnnule.AsEnumerable() _
Where (c!type.Equals("définitif") = True Or c!type.Equals("Transfert") = True) And c!date_annule <= dt2
Select c.Field(Of String)("num_recu")
Dim exceptData = (From c In query1.AsEnumerable() _
Where Not bannedCCList.Contains(c.Field(Of String)("num_recu")) _
).ToList

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 !