Sorting by Month in delphi - delphi

I am using Delphi 7 and Ms access 2007. I have a table called IndividualAccounts with the following field names in Ms access: Serial number, names, month paid, year paid. I have the following code to generate a report on a specific serial number I input.
procedure TReportsForm.BitBtn1Click(Sender: TObject);
var
qry :string;
begin
open;
SQL.Clear;
qry:= 'select*from IndividualAccount WHERE (((IndividualAccount.[Serial Number])=1))ORDER BY IndividualAccount.[Year Paid]';
SQL.Add(qry);
Active:= True;
reportform1.QuickRep1.Preview;
end;
I want to sort the report according to the calendar month order that is from January to December and year paid. What code can I add above to generate a report which orders the months in calendar order?

Assuming that the month paid and year paid columns are numbers and not strings, your query would need to look like this:
qry := 'SELECT * FROM IndividualAccount WHERE ((IndividualAccount.[Serial Number]) = 1) ORDER BY IndividualAccount.[Year Paid], IndividualAccount.[Month Paid]';
The rows will be sorted by year paid first, and then any rows that have the same year will be sorted by month paid.
A better solution would be to change the database to have a new date paid column that uses SQL's DATETIME date type. If you don't want to lose the existing month paid and year paid columns, you could create date paid as a calculated column that returns a DATETIME value calculated from the month paid and year paid column values using SQL's DateSerial() function (or change the month paid and year paid columns into calculated columns that use SQL's DatePart() or Month()/Year() functions to pull apart the value of the date paid column). Then you can sort rows in calendar order by sorting on the date paid column by itself:
qry := 'SELECT * FROM IndividualAccount WHERE ((IndividualAccount.[Serial Number]) = 1) ORDER BY IndividualAccount.[Date Paid]';

Related

Calculate week end date

I am working on HANA and I am not able to figure it out how to get the expected output.
Let me throw some light on getting the output. I am working on a procedure and my job is to get the data inserted in that particular table which I am successfully inserting, But the data is not in a correct manner.
I have 3 columns in my output named: report_date, report_week, week_end.
If suppose I start my data from 2010-01-01 the week end should start from 2010-01-06. And In this way I want my data from 2010 till 2030. It should show every week start in report_date and every week end start in week_end. The role of report_week is to show which week is going on currently.
My error output:
I have my procedure which I am posting below:
create procedure bhavya.zz_get_series()
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER
--DEFAULT SCHEMA <default_schema_name>
AS
LV_START_DATE date := '2010-01-01' ;
LV_END_DATE date := current_date ;
LV_WEEK_END NVARCHAR(10) := 'FRIDAY';
lv_report_date Date ;
Begin
TT_SERIES = (SELECT GENERATED_PERIOD_START AS REPORT_DATE,
week(add_days(generated_period_start , 2)) as report_week,
current_date as week_end --added ABHOOT
FROM SERIES_GENERATE_DATE ( 'INTERVAL 1 DAY', :LV_START_DATE,
ADD_DAYS(coalesce(current_date,:LV_END_DATE), 1)));
TT_WEEK_END = select report_week, max(report_date) as week_end
from :TT_SERIES
group by report_week ;
insert into "BHAVYA"."AFS_BASE.KPI.TABLES::DB_WEEK_SERIES"
(REPORT_DATE,REPORT_WEEK,WEEK_END)
select S.report_date, w.report_week, w.week_end
from :TT_SERIES S
left join :TT_WEEK_END W
on w.report_week = s.report_week;
end;
call bhavya.zz_get_series
Any help is really appreciated.
I think the problem is here:
week(add_days(generated_period_start , 2)) will return the week number within a year, so it will always be between 1 and 52. As week N will occur in 2010, 2011,...,2017 the max(report_date) will always be in the last year it occurs (so either 2016 or 2017).
TT_WEEK_END = select report_week, max(report_date) as week_end
from :TT_SERIES
group by report_week ;
So you have to extract the year as well from the report date and include it in the group by of the TT_WEEK_END select as well as in the join clause used for the INSERT statement.

Rails: select maximum date of each month

In my app users save a report each Friday for an organization. All my records in the reports table hold organization_id, day and workdays.
I want to get the sum of all workdays at the last Friday of each month.
With the following line I am able to select all reports for organization #8 and sum workdays for each Friday:
#all_report_sums = Report.where(:organization_id => 8).group(:day).select("day, SUM(workdays) AS sum_workdays")
The result:
[{"id":null,"day":"2017-02-03","sum_workdays":3},{"id":null,"day":"2017-02-24","sum_workdays":33},{"id":null,"day":"2017-04-07","sum_workdays":12}]
However in my output I only want the maximum dates of each month (which is the last Friday of each month) - so in my case this would be 2017-02-24 and 2017-04-07.
How can I achieve that?
This is what are you looking for
How to get the latest record from each group in ActiveRecord?
User.group(:user_id).having('day = MAX(day)')

Rails: How to group records that have the same Date (month day year) for a Datetime field?

I have a Purchase model and I want to group all of the records by their ordered_datetime field. However, I don't care about the time, I just want to group by the date. So if there are 2 orders ordered on:
5/12/2014 12:00PM
5/12/2014 3:00PM
They should be grouped together even though they happened at different times during the day.
Is there a way to do this? Purchase.uniq.pluck(:ordered_datetime) separates the 2 records into 2 groups since their times are different.
You can use the DATE function on the timestamp column:
Purchase.group('DATE(ordered_datetime)').count
Which returns each date with a purchase count.
You can also sort the dates by adding an order clause:
Purchase.group('DATE(ordered_datetime)').order('date_ordered_datetime').count

Stored Procedure to check leap year when entering the date

I want to write a procedure which will check whether entered date is a leap year or not.Kindly help me with this.
The following scalar function takes in a year and returns a bit flag indicating whether the passed in year is a leap year or not.
create function dbo.fn_IsLeapYear (#year int)
returns bit
as
begin
return(select case datepart(mm, dateadd(dd, 1, cast((cast(#year as varchar(4)) + '0228') as datetime)))
when 2 then 1
else 0
end)
end
go
Here are a few examples:
select dbo.fn_IsLeapYear(1900) as 'IsLeapYear?'
select dbo.fn_IsLeapYear(2000) as 'IsLeapYear?'
select dbo.fn_IsLeapYear(2007) as 'IsLeapYear?'
select dbo.fn_IsLeapYear(2008) as 'IsLeapYear?'
Explanation:
Giving the date as input to your custom sql function
The function takes in the year, appends '0228' to it (for February 28th) and adds a day.
If the month of the next day is a 2 (as extracted by the DATEPART function), then we're still in February so it must be a leap year! If not, it is not a leap year.

Is it possible to search for dates as strings in a database-agnostic way?

I have a Ruby on Rails application with a PostgreSQL database; several tables have created_at and updated_at timestamp attributes. When displayed, those dates are formatted in the user's locale; for example, the timestamp 2009-10-15 16:30:00.435 becomes the string 15.10.2009 - 16:30 (the date format for this example being dd.mm.yyyy - hh.mm).
The requirement is that the user must be able to search for records by date, as if they were strings formatted in the current locale. For example, searching for 15.10.2009 would return records with dates on October 15th 2009, searching for 15.10 would return records with dates on October 15th of any year, searching for 15 would return all dates that match 15 (be it day, month or year). Since the user can use any part of a date as a search term, it cannot be converted to a date/timestamp for comparison.
One (slow) way would be to retrieve all records, format the dates, and perform the search on that. This could be sped up by retrieving only the id and dates at first, performing the search, and then fetching the data for the matching records; but it could still be slow for large numbers of rows.
Another (not database-agnostic) way would be to cast/format the dates to the right format in the database with PostgreSQL functions or operators, and have the database do the matching (with the PostgreSQL regexp operators or whatnot).
Is there a way to do this efficiently (without fetching all rows) in a database-agnostic way? Or do you think I am going in the wrong direction and should approach the problem differently?
Building on the answer from Carlos, this should allow all of your searches without full table scans if you have indexes on all the date and date part fields. Function-based indexes would be better for the date part columns, but I'm not using them since this should not be database-specific.
CREATE TABLE mytable (
col1 varchar(10),
-- ...
inserted_at timestamp,
updated_at timestamp);
INSERT INTO mytable
VALUES
('a', '2010-01-02', NULL),
('b', '2009-01-02', '2010-01-03'),
('c', '2009-11-12', NULL),
('d', '2008-03-31', '2009-04-18');
ALTER TABLE mytable
ADD inserted_at_month integer,
ADD inserted_at_day integer,
ADD updated_at_month integer,
ADD updated_at_day integer;
-- you will have to find your own way to maintain these values...
UPDATE mytable
SET
inserted_at_month = date_part('month', inserted_at),
inserted_at_day = date_part('day', inserted_at),
updated_at_month = date_part('month', updated_at),
updated_at_day = date_part('day', updated_at);
If the user enters only Year use WHERE Date BETWEEN 'YYYY-01-01' AND 'YYYY-12-31'
SELECT *
FROM mytable
WHERE
inserted_at BETWEEN '2010-01-01' AND '2010-12-31'
OR updated_at BETWEEN '2010-01-01' AND '2010-12-31';
If the user enters Year and Month use WHERE Date BETWEEN 'YYYY-MM-01' AND 'YYYY-MM-31' (may need adjustment for 30/29/28)
SELECT *
FROM mytable
WHERE
inserted_at BETWEEN '2010-01-01' AND '2010-01-31'
OR updated_at BETWEEN '2010-01-01' AND '2010-01-31';
If the user enters the three values use SELECT .... WHERE Date = 'YYYY-MM-DD'
SELECT *
FROM mytable
WHERE
inserted_at = '2009-11-12'
OR updated_at = '2009-11-12';
If the user enters Month and Day
SELECT *
FROM mytable
WHERE
inserted_at_month = 3
OR inserted_at_day = 31
OR updated_at_month = 3
OR updated_at_day = 31;
If the user enters Month or Day (you could optimize to not check values > 12 as a month)
SELECT *
FROM mytable
WHERE
inserted_at_month = 12
OR inserted_at_day = 12
OR updated_at_month = 12
OR updated_at_day = 12;
"Database agnostic way" is usually a synonym for "slow way", so the solutions will unlikely be efficient.
Parsing all records on the client side would be the least efficient solution in any case.
You can process your locale string on the client side and form a correct condition for a LIKE, RLIKE or REGEXP_SUBSRT operator. The client side of course should be aware of the database the system uses.
Then you should apply the operator to a string formed according to the locale with database-specific formatting function, like this (in Oracle):
SELECT *
FROM mytable
WHERE TO_CHAR(mydate, 'dd.mm.yyyy - hh24.mi') LIKE '15\.10'
More efficient way (that works only in PostgreSQL, though) would be creating a GIN index on the individual dateparts:
CREATE INDEX ix_dates_parts
ON dates
USING GIN
(
(ARRAY
[
DATE_PART('year', date)::INTEGER,
DATE_PART('month', date)::INTEGER,
DATE_PART('day', date)::INTEGER,
DATE_PART('hour', date)::INTEGER,
DATE_PART('minute', date)::INTEGER,
DATE_PART('second', date)::INTEGER
]
)
)
and use it in a query:
SELECT *
FROM dates
WHERE ARRAY[11, 19, 2010] <# (ARRAY
[
DATE_PART('year', date)::INTEGER,
DATE_PART('month', date)::INTEGER,
DATE_PART('day', date)::INTEGER,
DATE_PART('hour', date)::INTEGER,
DATE_PART('minute', date)::INTEGER,
DATE_PART('second', date)::INTEGER
]
)
LIMIT 10
This will select records, having all three numbers (1, 2 and 2010) in any of the dateparts: like, all records of Novemer 19 2010 plus all records of 19:11 in 2010, etc.
Watever the user enters, you should extract three values: Year, Month and Day, using his locale as a guide. Some values may be empty.
If the user enters only Year use WHERE Date BETWEEN 'YYYY-01-01' AND 'YYYY-12-31'
If the user enters Year and Month use WHERE Date BETWEEN 'YYYY-MM-01' AND 'YYYY-MM-31' (may need adjustment for 30/29/28)
If the user enters the three values use SELECT .... WHERE Date = 'YYYY-MM-DD'
If the user enters Month and Day, you'll have to use the 'slow' way
IMHO, the short answer is No. But definitely avoid loading all rows.
Few notes:
if you had only simple queries for exact dates or ranges, I would recommend using ISO format for DATE (YYYY-MM-DD, ex: 2010-02-01) or DATETIME. But since you seem to need queries like "all years for October 15th", you need custom queries anyways.
I suggest you create a "parser" that takes your date query and gives you the part of the SQL WHERE clause. I am certain that you will end up having less then a dozen of cases, so you can have optimal WHEREs for each of them. This way you will avoid loading all records.
you definitely do not want to do anything locale specific in the SQL. Therefore convert local to some standard in the non-SQL code, then use it to perform your query (basically separate localization/globalization and the query execution)
Then you can optimize. If you see that you have a lot of query just for year, you might create a COMPUTED COLUMN which would contain only the YEAR and have index on it.

Resources