Trying to select second oldest record for each customer and group them by month shipped - postgresql

I'm trying to create a report which picks 2nd oldest order for every user and groups them by month/year. I know how to select the oldest order for each, but can't figure out how to get the second oldest.
The input data is a table which has every customers' order as a single row with the relevant columns being
order.id, order.user_id, order.date, product.name...
The ideal result I'm looking for is something like:
mon/year : number of second orders
12/2013 : 14
01/2014 : 2

Try this Code
select to_char(date_trunc('month',date),'MM/yyyy'),(select count(*) from order where date=min(p.date)) from order p
group by date_trunc('month',date)

Related

How to select max date value while selecting max value

I have the following sample from a table with students results with date for a school entry exam
First student passed exam - This is the most common record found for most students
Second student failed 1st time entry and passed second time based on the date
3rd student had a failed input entry and was corrected based on the Version
I need the results to like like the picture above, so we take into regard using the latest date and highest version!
My basic query thus far is
select studentid
,examdate --(Date)
,result -- (charvar)
from StudentEntryExam
How should I approach this issue?
demo:db<>fiddle
SELECT DISTINCT ON (studentid)
*
FROM mytable
ORDER BY studentid, examdate DESC, version DESC
DISTINCT ON returns the first record of an ordered group. In that case the groups are the studentids. You must find the correct order to set the required record first. So, you need to order by studentid, of course. Then you need the most recent examdate first, which can be achieved with DESC order. If there are two records on the same date, you need to order the highest version first as well using the DESC modifier, too.

In Postgresql, I counted/aggregated inventory based on part numbers, but want the query to only return results about a threshhold volume

For my company, I am writing a query that is aggregating/counting our inventory by part number. This works well and returns a data set that shows the volume we have in inventory for each part number.
However, because we have a large number of part numbers where the volume is just 1, I would like to exclude any such part number from the results when the count falls under a certain threshhold, like 5.
I've looked at the FETCH, LIMIT, and other functions but they don't seem to capture what I need.
select "Part#", "Description", "Cond_Code", "PO_NUM", count(*)
from "Inventory"
group by "Part#","Description","Cond_Code", "PO_NUM"
Order by "count" DESC,"Part#", "Description","Cond_Code", "PO_NUM"
This gives me the results where each part number total is displayed, but as I said, I would like to display only part numbers where the totals meet a certain minimum threshhold.
You need a HAVING clause:
select "Part#", "Description", "Cond_Code", "PO_NUM", count(*) "Counter"
from "Inventory"
group by "Part#","Description","Cond_Code", "PO_NUM"
having count(*) > 4
order by "Counter" desc, "Part#", "Description","Cond_Code", "PO_NUM"

How to sort combo box by frequently used?

So, simple question, I have combo box in my database and I want items that I have selected most frequently to appear first the next time that I add a record.
I would suggest adding a Long Integer field to the table consituting the row source for your combobox, and incrementing the value held by such field either on the AfterUpdate event of the combobox, or following the main operation being performed by your form.
Then, sort the items in the combobox by this new field in descending order.
I assume that your combo box selects a lookup value in for a property (PropertyID) that is saved in a table (MainTable).
You can get the number of times this property has been selected with
SELECT PropertyID, COUNT(*) AS SelectedTimes
FROM MainTable
GROUP BY PropertyID
Now get the sorted lookup table by using this query as sub-query:
SELECT L.PropertyID, L.Name
FROM
LookupTable L
( SELECT PropertyID, COUNT(*) AS SelectedTimes
FROM MainTable
GROUP BY PropertyID) X
ON L.PropertyID = X.PropertyID
ORDER BY X.SelectedTimes DESC, L.Name
I'm also sorting by name in case two entries have the same count.
As usage may change over time, you should record the time when an item was selected. Then you can weight the usage, so recent usage of an item have higher weight than those items used, say, a year ago.
Then you can run a query to list the usage having the most recently used items at top:
Select Item, Sum(1 / DateDiff("h", [SelectedTime], Now())) As Usage
From ItemUsage
Group By Item
Order By Sum(1 / DateDiff("h", [SelectedTime], Now())) Desc
Of course, this linear weighting may be too simple. You can apply any math to the usage like square or log.

Reporting a count in 2 different tables

I'm working in a Crystal Report that someone else created. In the report I want to count the total number of days someone is absent. The statement below is what is currently in place.
(select count(*) from attend_day inner join absencetype on name=attend_type
where GRP='Absent')
However it isn't giving me the correct number. it gives me some outrages number like 1,500. The table I'm working with are Attendance Table.
In the Attendance Table there is ATTEND_TYPE which is Attendance entry for the student and I want to total the number of days that have the word Absent in them. There are 2 values Absent - Excused and Absent - Unexcused.
Any suggestions?
Try writing a formula called "Absent":
iif(Attendance.ATTEND_TYPE like "*absent*", 1, 0)
Then insert a summary that takes the SUM of #Absent

Referencing first record in a group in crystal reports

In my report, in group footer, I want to add the sum on a column from all records in the group except the first one. How can I do that?
I tried Insert - Subtotal but it adds all records. If I can access the first record from each group, I can subtract it from the sum.
Let's say you're grouping your report by {Table.GroupID} and want to get the total per group, excluding the first record in the group, for {Table.NumericField}.
You can do this by creating a running total where:
Field to summarize: Table.NumericField; Type of summary: Sum
Set to evaluate with a formula: previous({Table.GroupID})={Table.GroupID}
Reset on change of group
The second step ensures that the group total is updated for every record except the first one in the group and can be read as "Only evaluate this running total when the previous record's GroupID is the same as the current record's GroupID.