I want to count the number of non-null values per column in a Datatable. I could loop through the columns and use the compute function on each column, but I was wondering if there is a more efficient way to do this.
You could add a column with an expression that checks whether the rests of the columns are null, see http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(VS.80).aspx
Then you can Compute on that column.
I think that the Compute function is quite appropriate in this context. You could use code similar to the following:
For Each col as DataColumn in myTable
Dim aggExpr as string = string.format("Count{0}", col.ColumnName)
Dim filterExpr as string = string.format("{0} IS NULL", col.ColumnName)
Dim myCount as integer = CInt(myTable.Compute(aggExpr, filterExpr))
Console.WriteLine(myCount)
Next
(Typed in here, watch for syntax)
Note that I say "similar to the following". Please add appropriate error/null value checks.
Related
Very new to access VBA and would love some guidance on this.
I am searching through a string and looking for a particular substring in this field. This substring would have a value based on another table, ie
order = "Reference order QQ131415"
The problem is, there is no particular pattern for order numbers. Some are 7 digits, some are 10 and some have dashes in there.
There is a table i have access too that has these order numbers though, and I guess I am trying to use that table as a dictionary.
my very very basic Access VBA code is like this
' order= Instr(1, rst![order], qst![order_id],vbBinaryCompare)'
order is the string where i have the order id i am trying to extract
order_id is the actual id from a seperate table.
Is this something that Access VBA can handle?
So i think this will help you
You're not very clear in the sentence following on from "order=" with your code. Could you clear that up.
Instr(string1, String2, [ compare ])
string1 Required. String expression being searched.
string2 Required. String expression sought.
Instr returns a Variant (number in this case) specifying the position of the first occurrence of one string within another. So it should be:
Position= InStr(1, string1, string2, 1)
So you'd now know that the ordernumber starts at position x in Order. You'd then have to do a left(Order, Len(order) -x) to extract the string.
Youd do that in a nested loop because youll have to loop through your dictionary per record in Order.
E.g.
Dim rsOrder as DAO.recordset
Dim rsOrderId as Dao.recordset
dim orderTest as integer
dim stringcapture as string
Set rsOrder = Currentdb.OpenRecordset("[SELECT STRING]")
rsOrder.Movefirst
Do until rsOrder.EOF or rsOrder.BOF
Order = rsOrder![OrderFieldName]
Set rsOrderId = Currentdb.OpenRecordSet("[SELECT STRING]")
rsOrderID.Movefirst
Do Until rsOrderID.EOF or rsOrderID.BOF
OrderID = rsOrderID![OrderIDFieldName]
orderTest = Instr(1, Order, OrderID,1)
StringCapture = left(Order, Len(order) -OrderTest)
rsOrderID.movenext
Loop
rsOrder.movenext
Loop
rsOrder.close
rsOrderID.close
Something to that affect.
I have a datatable and I need to be able to sort either asc or desc by the jobcode column. Unfortunately the column field values contain both numbers and letters like this.
HD1233
HD12333
PG2839
TP9383
I need to extract the numbers, sort numerically and then put it back. So the above would look like this in the output.
HD1233
PG2839
TP9383
HD12333
I have a piece of code which does some sort of sort which is like this ...
Dim dtOut As DataTable = Nothing
dt.DefaultView.Sort = Convert.ToString("jobcode" & Convert.ToString(" ")) & drpAscorDesc.SelectedItem.Text
dtOut = dt.DefaultView.ToTable()
Im just unable to do it properly without the letters. Any advice would be greatly appreciated.
Add another column of type Integer to your DataTable.
Iterate through all DataRows, put values into new column based on job codes in these datarows (read value -> delete all non-numeric characters -> Int32.TryParse()).
Sort by new column.
I have created an array from a CSV of date values and now need to be able to sort them so that I can then get the latest date from the array.
I have tried:
Array.Sort()
but this doesn't sort correctly, I suppose because the array values are strings, any body got any ideas??
Thanks for any help.
CODE USED TO CREATE ARRAY
'array string exampel: "19/07/2012,23/07/2012,23/07/2012,19/07/2012,25/07/2012"
Dim ArrDates As Array = ArrDates .Split(",")
SOLUTION
Dim ArrAgentsReportCheck As Array = AgentsReportCheck.Split(",")
Dim ArrDates As New List(Of Date)
For i As Integer = 0 To ArrAgentsReportCheck.Length - 1
ArrDates.Add(ArrAgentsReportCheck(i))
Next
ArrDates.Sort()
Dim LatestDate As Date = ArrDates.Max()
ArrDates = ArrDates.OrderBy(Function(d) DateTime.ParseExact(d, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)).ToArray()
Alternately, you can use OrderByDescending() depending upon your needs.
As astander said, It is very complicated to sort a array having datetime values. Instead just convert the array to List or ArrayList and make your life easy.
For ArrayList you can use the following syntax:
List<DateTime> dates = ... // init and fill
dates.Sort();
dates.Reverse();
One way would be to convert strings to DateTime using DateTime.ParseExact
Another way just to write your own IComparer and pass to Array.Sort
i have a group of values like below pattern
name: color: percentage:
i need to sort this data in desc order of percentage
now i am using data-table DefaultView sort method
//declare columns
DataTable dt = new DataTable();
dt.Columns.Add("name");
dt.Columns.Add("color");
dt.Columns.Add("percentage");
//adding rows
DataRow dr = dt.NewRow();
dr["name"]="a";
dr["color"]="red";
dr["percentage"]="10.1";
dt.Rows.Add(dr);
//sorting
dt.DefaultView.Sort="percentage desc";
the problem is coming when the same number [percentage] is repeating more times
any idea where is the error?
Change this code:
dt.Columns.Add("percentage");
to this:
dt.Columns.Add("percentage", typeof(double));
As multiple people have pointed out, because you added the percentage as a string ("10.1") it's going to be sorted as a string. That means, since you're sorting in descending order, that "2" will appear above "10.1" in your sort. That's because string values are compared character by character, and "2" comes before "1" in a descending alphabetic sort.
Is that the problem you are talking about? If so, either of the other proposed solutions will work for you.
You also said "the problem is coming when the same number [percentage] is repeating more times" If you want a secondary sort column, which affects the order of records with the same primary sort column value (percentage), you have to specify one:
dt.DefaultView.Sort="percentage desc, name asc, color asc";
I'm using DateDiff() function of ASP to find the date difference between two dates.
The Function works fine and displays the exact date difference between two dates but when it comes to insert this value in the database it takes 9 as the value irrespect of any date difference.
Suppose difference between two dates is more than 15 or 20 days, in the database it takes "9".
I have used INT as the DATA TYPE for the column where it displaying the date difference.
Is DATA TYPE creating an issue here?
I even tried using session variable to store the value but no luck - here's my code below:
if request.Form("sub") <> "" then
sql = "Select * from emp_leave_details"
rs.open sql , con, 1, 2
dim diff
dim todate
dim fromdate
fromdate= rs("leave_from")
todate= rs("leave_to")
session("date_diff")=datediff("d",fromdate,todate)
rs.addnew
rs("emp_name") = request.Form("name")
rs("emp_no") = request.Form("number")
rs("address") = request.Form("address")
rs("contact_no") = request.Form("contact")
rs("mobile_no") = request.Form("mobile")
rs("contact_onleave") = request.Form("contact_details")
rs("leave_type") = request.Form("rad")
rs("other_leave_details") = request.Form("PS")
rs("leave_from") = request.Form("from")
rs("leave_to") = request.Form("to")
rs("applied_by") = request.Form("apply")
rs("accepted_by") = request.Form("accept")
rs("approved_by") = request.Form("approve")
rs("no_of_leave_taken")= session("date_diff")
rs.update
response.Write("<script language='javascript'>{update();}</script>")
rs.close
end if
The datatype has nothing to do with this. Storing the value in the session is not the solution. You can use a regular variable.
From your code it looks like you always use the same values for fromdate and todate. This is because you do not iterate the rows in the resultset.
if not rs.bof and not rs.eof then
do while not rs.eof
'' code to execute for each row
rs.moveNext
loop
end if
In your current script rs will always return the results of the first row returned by the query.
The second problem your running into might be the Date datatype. Convert your value to a date using cDate and use this to calculate the difference.
Your problem is , you search for "Select * from emp_leave_details" which always gives all records from that table. You retrieve the values of the first record and do a diff of these, which results in always the same value, that is normal. From your question it is unclear what you really want to do. I suppose so want so select a record like
Select * from emp_leave_details where emp_name=<%=request.Form("name")%>
and based on that add a new record with a computed no_of_leave_taken.
Sorry guys my bad...
It was the database field name that I was calling instead of
fromdate= request.form("from")
todate= request.form("to")
I was calling this
fromdate= request.form("leave_from")
todate= request.form("leave_to")
Sorry again..but I really appreciate you all for providing me with all that possible solutions.
Thanks.