Filtering a Datatable using Select() - c#

I have a DataTable (dt) as
StartDate EndDate Price
1 3 10
4 6 12
7 10 16
11 15 20
I want to filter the Values from dates between fromdate= 2 and todate=8.
so i am expecting the result to be
StartDate EndDate Price
1 3 10
4 6 12
7 10 16
I have used the vb Datatable Select as->
dt.Select("StartDate <= #" & fromdate& "# And EndDate >= #" & todate& "#")
but i am not getting the result. Can u please suggest me..

Your query should be like that:
dt.Select("StartDate <= #" & todate & "# And EndDate >= #" & fromdate & "#")
to find records that overlap with your range.

it should be
dt.Select("StartDate >= " & fromdate & " And EndDate <= " & todate)
Two problems
Your operator were all wrong. You were taking startdate less than 2 and greater than 8 whereas it should be startdate greater than 2 and less than 8
Morever no need for # assuming that columns are of integer type.

Use the DateDiff function, my friend

Related

Custom sequence of reference Id on the basis of DateTime in Sql Query

Is it possible to write an sql query that returns
18315-0921
The result is time based where
18 means 2018
315 means day of the year
0921 means present time.
declare #TDATE as datetime2 = getdate();
select Right('0' + CAST(YEAR(#TDATE) % 100 as varchar(2)) , 2)
+ RIGHT('00' + CAST(DATEPART(y,#TDATE) as varchar(3)) , 3)
+ '-'
+ REPLACE(CONVERT(varchar(5),#TDATE, 114), ':', '');
so I'm getting the Year number in 2 digits by taking the modulus 100 of the year , e.g. 2014 % 100 is 14
then I'm changing that to a string, with a leading '0' if needed
To get the day number of the year, I'm using DatePart with 'y' to indicate 'day of year number' and that is padded with up to 2 digits if needed.
To get the time I'm converting to hh:mi:ss:mmm, but only keeping the first 5 chars, then I'm replacing the ':' with nothing
Per #Rob's suggesion in the comments you can do this via: Example
declare #myDateTime DateTime = getutcdate()
select format(#myDateTime, 'yy')
+ format(DatePart(dy, #myDateTime), '000')
+ format(#myDateTime, '-HHmm')
However, the ddd part isn't available this way, since ddd would convert to the weekday name: i.e per documentation. That said, you can use this to simplify the above: Example
Original solution:
Here's a solution: Example
declare #myDateTime DateTime = getutcdate()
--to get the component parts
select DatePart(YEAR, #myDateTime) - 2000 YY
, DateDiff(Day, DateFromParts(DatePart(YEAR, #myDateTime),1,1), #myDateTime) DDD
, DatePart(Hour, #myDateTime) HH
, DatePart(Minute, #myDateTime) MM
--to format as a single string
select right('0' + cast(DatePart(YEAR, #myDateTime) - 2000 as varchar(10)), 2)
+ right('00' + cast(DateDiff(Day, DateFromParts(DatePart(YEAR, #myDateTime),1,1), #myDateTime) as varchar(10)), 3)
+ '-'
+ right('0' + cast(DatePart(Hour, #myDateTime) as varchar(10)), 2)
+ right('0' + cast(DatePart(Minute, #myDateTime) as varchar(10)), 2)
DatePart(YEAR, #myDateTime) - 2000 gives us a 2 digit year by getting the full year (e.g. 2018 as a number, then pulling back just those digits we're interested in by subtracting 2000)
DateDiff(Day, DateFromParts(DatePart(YEAR, #myDateTime),1,1), #myDateTime) gives us the number of days since the 1st Jan in the date's year (given by DateFromParts(DatePart(YEAR, #myDateTime),1,1)) up to the given date (so 1st Jan would be 0; if you wanted 1st Jan to be 1, just add 1 to this result).
The hour and the minute value are just given by pulling back those date parts.
When we create the string we cast these numeric results to strings (varchar) and concatenate them.
The right('0' + /*...*/) part allows us to right pad the digits with leading zeros, so if the time's 09:05 we get 0905 instead of 95.
You can get almost what you're after by using the native format command; e.g.
select format(#myDateTime, 'yy-HHmm')
However, the ddd part isn't available this way, since ddd would convert to the weekday name: i.e per documentation. That said, you can use this to simplify the above: Example
select format(#myDateTime, 'yy')
+ right('00' + cast(DateDiff(Day, DateFromParts(DatePart(YEAR, #myDateTime),1,1), #myDateTime) as varchar(10)), 3)
+ format(#myDateTime, '-HHmm')

7-digit Julian Date to Normal Calendar Date

How do I convert a 7-digit Julian Date (2016092) to a regular Calendar date (MM-DD-YYYY)?
I was thinking of taking the last three digits and converting it to a regular date then appending the first four digits as the year but I'd have to consider leap years.
Expected output: 04-01-2016
My current (SQL) code which solves the problem is
DECLARE #dt char(7)
SET #dt = 2016092
SELECT DATEADD(dd, CAST(RIGHT(#dt, 3) AS int) - 1, CAST(LEFT(#dt, 4) AS datetime))
How can I implement it on C#?
You don't have any kind of Julian Day (Date) format which is
https://en.wikipedia.org/wiki/Julian_day
But a kind of custom format which can be reconstructed from the sql provided:
year * 1000 + days from 1st Jan + 1
So 2016092 means year 2016 and 092 - 1 = 91st day from the 1st of Jan (1st of Apr)
Implementation:
int source = 2016092;
DateTime result = new DateTime(source / 1000, 1, 1).AddDays(source % 1000 - 1);
Console.WriteLine($"{result:MM-dd-yyyy}");
Outcome:
04-01-2016

Filter Date by FinancialYear

I have a table where i needed to filter the data by financial year.
Financial year is between April 1 of current year and March 31st of next year.For example:The current year is 2016 so the current financial year comes between April 1 2016 and March 31 2017.
The table
Id CenterId SlNo Date
1 1 5 2016-01-09 10:51:43.480
2 2 10 2016-01-09 10:51:43.480
I wanted to get the Slno where the CenterId=1 and Date will between current financial year.
My concern is Do i need another column of date for filtering financial year.
Any help is highly appreciated?
No you can do it without creating a new column. Simply calculate the current financial year dates like this:-
DateTime currentFinancialYearStartDate = new DateTime(DateTime.Today.Year, 4, 1);
DateTime currentFinancialYearEndDate = new DateTime(DateTime.Today.Year + 1, 3, 31);
Then, Simply use them in your filter like this:-
var result = dbContext.Sample.Where(x => x.CenterId == 1
&& x.Date >= currentFinancialYearStartDate
&& x.Date <= currentFinancialYearEndDate)
.Select(x => x.Slno);

How to select current dates from current month

I would like to retrieve the data between 1 -30 of the current month [ i am using MSACCESS Dbase to do so] Below is the query that i am trying --
SELECT count(usercategory) as category_count ,usercategory FROM user_category
where IssueDate between DATEADD('m', DATEDIFF('m', 0, DATE()) - 0 , 0) and DATEADD('m', DATEDIFF('m', 0, DATE()) + 1, - 1 ) group by usercategory
Data that i am holding in my MSACCESS Dbase -
Category1 9/7/2013 12:00:00 AM
Category1 9/8/2013 12:00:00 AM
Category2 10/8/2013 12:00:00 AM
so output should have only 2 records
but my query is giving no results
Here is the query I think you need. All the functions it uses are always available in Access SQL regardless of whether the query is run from within an Access session or from without (as in your c# situation).
The db engine will evaluate both those DateSerial expressions once, then use their results to filter the result set. This approach will be especially fast with an index on IssueDate.
SELECT
Count(usercategory) AS category_count,
usercategory
FROM user_category
WHERE
IssueDate >= DateSerial(Year(Date()), Month(Date()), 1)
AND IssueDate < DateSerial(Year(Date()), Month(Date()) + 1, 0)
GROUP BY usercategory;
Here is an Access Immediate window session which explains the logic for those DateSerial expressions ...
? Date()
9/6/2013
? Year(Date())
2013
? Month(Date())
9
' get the date for first of this month ...
? DateSerial(Year(Date()), Month(Date()), 1)
9/1/2013
' now get the date for the last of this month ...
? DateSerial(Year(Date()), Month(Date()) + 1, 0)
9/30/2013

Concat columns adding data in datatable

I am getting some data from database that has date break up in year month and year due to some reason i want to concat the column and add a new column.
What i am doing is adding the data
DataColumn newColumn;
newColumn = new DataColumn("CompositeDate");
newColumn.Expression = "Day + Month + Year" ;
scaleResponseData.Columns.Add(newColumn);
the data in the data table is some thing like this
year | Month | Day
2009 10 2
2010 11 3
What my current code is doing
year | Month | Day | composite_Date
2009 10 2 2021
2010 11 3 2024
But the result should be some thing
year | Month | Day | composite_Date
2009 10 02 20091002
2010 11 03 20101103
I have different combination but nothing is working
Try this:
newColumn.Expression = "Convert(Day , 'System.String') + Convert(Month , 'System.String') + Convert(Year, 'System.String')";
This is because your columns are numbers and adding three numbers will yield a new number.
Try to force the expression to make a string by including an empty text between the columns:
newColumn.Expression = "Day + '' + Month + '' + Year" ;
Yoo can also convert that to "real" DateTime type, like this.
newColumn.Expression = "Convert(Year + '/' + Month + '/' + Day, 'System.DateTime')";
If you have year, month and date as ints in database they are added numerically, say:
Year = 2009, month = 10 and day = 2 == 2009+10+2 = 2021, which is your current composite_date.
You should probably try
year * 10000 + month * 100 + day to get the result you desire => newColumn.Expression = "Day + Month * 100 + Year * 10000" ;

Categories