I have this vehicle_data table: CREATE TABLE public.vehicle_data
CREATE TABLE vehicle_data
(
model_name text NOT NULL,
record_date text NOT NULL,
inv_quantity integer,
CONSTRAINT vehicle_data_pkey PRIMARY KEY (model_name, record_date)
)
My table looks like:
model_name record_date
car1 5-2015
car1 1-2016
car1 2-2015
car2 2-2017
car3 8-2016
When I run my function to search for any car, I would like to obtain as a result that orders the entries by month and then by year, so far car1, it should lok like this:
model_name record_date
car1 2-2015
car1 5-2015
car1 1-2016
Since my record_date is TEXT, I thought that in my function I could split the TEXT array using split_part(record_date,'-',2) to get the year value, store all the unique values in an array, then run my select query for each year.
CREATE OR REPLACE FUNCTION getdata(model text)
RETURNS TABLE(a text, b text) AS
$BODY$
DECLARE i int;
list TEXT[]:= ARRAY(SELECT DISTINCT split_part(record_date,'-',2) as xyz
from vehicle_data
order by xyz);
BEGIN
i:=0;
WHILE i < (select cardinality(list)-1) LOOP
RETURN QUERY
select model_name, record_date
from vehicle_data
where model_name LIKE model AND split_part(record_date,'-',2) LIKE list[i]
order by length(record_date), record_date ASC;
i:=i+1;
END LOOP;
RETURN;
END;
$BODY$
LANGUAGE plpgsql;
Although the function does work, it duplicates the results 68 times, rather than stopping.
car1 1-2016part of the expected result? It has a different year than the other two rows. I would have expected you only want2-2015and5-2015in the returned resultselect model_name, record_date from vehicle_data where model_name = 'car1'