Access Database - Most Recent Record - Max Function - sql

I'm in the process of building a database to keep track of loaning equipment. I'm trying to build a query that will display the latest record of each machines location.
Relevant table is:
Movements:
Movement ID (PK)
EntryDate (Automatically generated on record entry)
Serial (FK from a table called stock, with (Make, Model etc)
Location (Where the machine is)
Status (Things like: Available, Testing, Sold etc)
Current query is:
SELECT Movements.Serial, Max(Movements.EntryDateMovements) AS MaxOfEntryDateMovements
FROM Movements
GROUP BY Movements.Serial;
Which spits out the latest date of a record, and the serial associated with it.
What I need is the status to be shown in the results, but it still be grouped by the serial.
My issue is that when I try and add that, it either comes back with an error with about the expression not being part of the aggregate function, or I get more results than expected, as it no longer just keeps the results unique to the serial.
I'm pretty new Access, and have so far been able to muddle through guides, and books, and this site, to get everything else working, but i'm stuck at this hurdle.
Any help would be much appreciated.

Select top 1 *
from Movements
order by EntryDateMovements desc
This will give you everything for the newest record. This is TSQL but I think it carries over to Access.

Try this
Select t.serial,t.EntryDateMovements ,t.location, t.status
From movements as t
Inner join (SELECT Movements.Serial, Max(Movements.EntryDateMovements) AS MaxOfEntryDateMovements
FROM Movements
GROUP BY Movements.Serial) as MaxMovements on t.serial= MaxMovements.serial and t.EntryDateMovements=MaxMovements.MaxOfEntryDateMovements

Related

SQL Database "Operation must use an updateable query" Workaround

So my basic goal is to create a database for a shopsystem, which is my task to do for my IT course. I tried to create a UPDATE-Query, that collects all the Sale Positions ("tblPosition.PositionAnzahl") ordered with a SELECT-Query and groups it by the products ordered, to have an overview about how often each product has been sold.
I want to do this to keep track of how many items are still left in the inventory.
The Query was supposed to update 1 field ("tblArtikel.ArtikelVerkauft") in my table "tblArtikel", in which all my articles and their information is stored.
However, i just found out that you cannot run UPDATE-Queries, that use SELECT-Query data, as i get a error, that says "Operation must use an updateable query".
This is the code i used for the query:
UPDATE tblArtikel as a JOIN
(SELECT p.PositionArtikelID, Sum(p.PositionAnzahl) AS SumOfPositionAnzahl
FROM tblPositionen as p
GROUP BY p.PositionArtikelID
) p
ON a.ArtikelID = p.PositionArtikelID
SET ArtikelVerkauft = p.SumOfPositionAnzahl;
Is there another way to keep track of all the Items left in my inventory, apart from doing what i did?
Here are screenshots of the 2 tables (the depending fields are circled red):
tblPositionen with field PositionAnzahl
tblArtikel with field ArtikelVerkauft
I have not worked with SQL before and only learned about it during 45 min, so ther emight be an easy way for this, but i would still appreciate every answer from you guys.

Multiple aggregates via join in Teradata

I have two tables
Email Contact History
Place of Service
that share a primarymembercustomerid. The Email Contact History has three fields:
Campaigncode
Primarymembercustomerid
maildate
and the Place of Service table has three fields
primarymembercustomerid
servicedate
serviceshortDesc
primarymembercustomerids are selected for E-mail campaigns, then if they walk into one of our branch offices and receive services, they show up in the Place of Service table. I want to count the number of primarymembercustomer ids that are mailed, and right next to it I want to have a count of primarymembercustomerids that showed up to a branch office.
What I have so far:
select
ch.campaigncode,
pos.serviceshortdesc,
count(ch.primarymembercustomerid),
count(pos.primarymembercustomerid)
from mktprodvm.cdmv_prmmbr_contacthist_email ch
right outer join mktprodvm.cdmv_pos pos on ch.primarymembercustomerid = pos.primarymembercustomerid
where ch.campaigncode = 'EDT_ALLACMO'
and pos.servicedate between '2017-02-01' and '2017-02-28'
group by 1,2
What I'm ending up with is a count of primarymembercustomerids that walk into a branch for that time period, but I'm not getting the total count of primarymembercustomerids that were E-mailed. I thought that by doing a right outer join I would get the total number of primarymembercustomerids that were mailed, but it's not working for me. I feel like I need to do some kind of subquery or correlated subquery, but I've ready about how to use them and I don't think that's right. I've never used them before and to be quite honest I'm not that great of a SQL coder either. Thanks for any help!
Because my low reputation on this site I can't comment, so I'm writing this as an answer.
I think that you are using the wrong type of join (or writing the tables in the wrong order). If you don't want to lose rows of your main table, the Email Contact History, you have to do a LEFT JOIN not a RIGHT JOIN.
Also, I don't know if it's possible, but I'm guessing that a primarymembercustomerid can have more than one service and since you are selecting the serviceshortdesc, a single Email might count in different rows of your anwerset and the total won't be accurate. According to what you said you want, I don't see a reason for including the service description in the SELECT.

Jira: Status of all tickets at a certain point in time

I want to pull out month-by-month stats from a jira project, which shows the number of tickets that were in each state at the start of each month (similar to the Cummulative Flow Diagram, but extractable).
Is there a way in JQL or SQL to get the status of all tickets in a project at a specific point in time?
If you want to do this via SQL for one specific date, Atlassian provides instructions for related useful queries on JIRA 4.x. A particularly-relevant one would seem to be the "Find Statuses of all issues in a project on a given date" query, but it will be a bit of an uphill battle to do this over a varying date range.
These queries are still mostly relevant for more modern versions of JIRA, with the main concern being that the JI.pkey column will be blank in JIRA 6+. To get this data back, you first need to join with the project table with ON project.id=JI.project, and then synthesize the issue key yourself as P.pkey || '-' || JI.issuenum. You will also probably need to apply typecasts to some of the joins (at least on some databases) since a few joins are trying to relate integer-typed columns with text columns.
For reference, their JIRA 4.x query was the following:
SELECT JI.pkey, STEP.STEP_ID
FROM (SELECT STEP_ID, ENTRY_ID
FROM OS_CURRENTSTEP
WHERE OS_CURRENTSTEP.START_DATE < '<your date>'
UNION SELECT STEP_ID, ENTRY_ID
FROM OS_HISTORYSTEP
WHERE OS_HISTORYSTEP.START_DATE < '<your date>'
AND OS_HISTORYSTEP.FINISH_DATE > '<your date>' ) As STEP,
(SELECT changeitem.OLDVALUE AS VAL, changegroup.ISSUEID AS ISSID
FROM changegroup, changeitem
WHERE changeitem.FIELD = 'Workflow'
AND changeitem.GROUPID = changegroup.ID
UNION SELECT jiraissue.WORKFLOW_ID AS VAL, jiraissue.id as ISSID
FROM jiraissue) As VALID,
jiraissue as JI
WHERE STEP.ENTRY_ID = VALID.VAL
AND VALID.ISSID = JI.id
AND JI.project = <proj_id>;
If you are open to using a commercial add-on, Arsenale Dataplane can do exactly what you want in a few clicks using the Issue Values Snapshots by Date report. Disclaimer: I work for the company that makes this product.
With JQL you can only look for Issues not for States. About the specific point of time, you can only get information about the current status, unless you develop a complex script that takes in account the current situation and the changes made after the date you want to check (ChangeHistoryManager).
On the other hand, you can configure a Board with a pie chart (in example), where you set the Status field to be shown. Additionaly, you can create a Notification so that each first of month you get an email with this information.
Probably more interesting the scripting solution, but absolutely longer in time, and more complex.
Regards

MS Access manual Auto incrementing field

Im building a system for my company to keep track of internal orders, inbetween our warehouses, we have material that goes out warehouse 1 to warehouse 2 and we kind of lose track of how much of "x" is in warehouse 1 and how much in warehouse 2, so i want to implement this access db where a user fills a form and says: order 1: 500 of "x" order 2: 300 of "y". then another user fills an exit form where he says 1 of "x" going out, so i would need the program to keep track of total order and how much as gone out to fill order 1 and so on...
My idea here is to have both an order number and an id number for each of "x" everytime someoneone assembles 1 "x" they fill the form and print a label directly from the access (i have this part working already) while keeping a record of when it was assembled, who verified and what was verified (it will work as a quality control also).
What i dont know is how to program the db so when it reaches 500 of "x", the id number for "x" starts again from 1
This is the one major issue with my program right now, i'm not experienced in access db's or vba, but im getting there with a tip and a trick from here and there, so, no need to be careful with the technical language, i will google it if i have to :p
EDIT:
The table structure goes as follows:
1 table as the main table where I record the check that is made for every product, where I include the model of the product, the said ID that I want to reset after a number of products checked, and a concatenated field that includes most of this information to generate a qr code.
Then there is a table for the Order Number, which is connected to a form to record each new order with a date/time field, the order number itself and the number of products. This number of products must then be called from the code that will count how many products have been checked to date and keep the order number field updated so we can keep track of the order.
Then there is another minor table just to get values for the form, the product models
Thank you for your answers ;)
See this MSDN Documentation
Unfortunately in Access, you cannot 'reset' an ID field, unless you move the records to a newly created table and use that table for every 500 records.
As for the user control and login form, I'm afraid those are separate questions that must be asked in a different thread.
To get you started:
You can set the RecordSource of a form to a table, and when users make entries, the data will be saved to the table. You can also use a form with controls (text boxes, comboboxes, etc.) and create a button that runs a query to insert these records into a table.
The login piece - you can encrypt the database with a password. That may/may not be sufficient.
I would suggest you change your schema, if possible. Something like the following:
Orders
OrderID (Autonumber)
ProductID (link to your Products table)
QuantityRequested
Deliverables
DeliverableID (Autonumber)
OrderID (link to your Orders table)
SequenceNumber: in the BeforeInsert event set this value equal to:
DCount("*", "Deliverables", "OrderID=" & Me.OrderID) + 1
I'm assuming that your form has a control named OrderID that is bound to the OrderID field of the Deliverables table.
The code uses the DCount() function to get the count of all the other deliverables that have already been created for this order. If this is the first deliverable, DCount() will return 0. It then adds 1 to this count to get the sequence number of the next deliverable.
If the new SequenceNumber is greater than the quantity requested, you could display a message saying that the order has been filled and cancel the creation of the Deliverable record.
This is just one approach and it is not a complete solution. I'm assuming that once assigned a sequence number a deliverable cannot be deleted. You might need to make allowances for deliverables that get lost or damaged. You could incorporate a status field to the Deliverable table to deal with this, but you would still need to make a decision about what to do with the SequenceNumber.

SQL Server Query: Daily Data Snapshot Comparison (Counting Delta Occurrences)

I am working towards counting customer subscription ("package") changes. To do this, I am selecting all data from my package table once, every day. I am calling the daily query results "snapshots" (approx 500k rows). I then load the snapshot data into a new table. After 10 days I have a total of 5 million rows in the snapshots table (500k rows * 10 days). The majority of customers do not changes packages (65%). I need to report which customers, of the remaining 35%, are switching packages, when they are switching packages, what package changes they are making (from "package X" to "package y") and which customers are changing packages most frequently.
The query I have written uses a self-join. I am identifying the changes but my results contain duplicate rows.
This is my query:
select *
from UserPackageDump UPD1, UserPackageDump UPD2
where UPD1.user_id = UPD2.user_id
and UPD1.package_id <> UPD2.package_id
How can I change this query to yield only distinct results?
SELECT
DISTINCT *
FROM
UserPackageDump UPD1
JOIN UserPackageDump UPD2
ON UPD1.user_id = UPD2.user_id
WHERE
UPD1.package_id <> UPD2.package_id
You have many options for doing this, and I'm not sure your approach is the right one to take. Firstly to answer your specific question, you could perform a DISTINCT as per #sqlab's answer. Or you could include the date in the join, ensuring that UDP1 only matches a record in UDP2 that is one day different.
However, to come back to the approach, there should be no need to take a full copy of all the data. You have lots of other options for more efficient data storage, some of which being:
Put a "LastUpdated" datetime2 field in the database, to be populated each time the row is changed. Copy only those rows that have a LastUpdated more recent than the last time the copy was made. Assuming the only change possible to the table is to change the package_id then you will now only have rows in the table for users that have changed.
Create a UserPackageHistory table into which rows are written each time a user subscribes to a package, at the same time that UserPackage is updated. This then leaves you with much the same result as the first bullet, but in advance of running the copy job.
Then, with any one of these sets of data, to satisfy the reporting requirements you could populate a cube. Your source would be a set of rows containing user_id, old_package_id, new_package_id and date. You would create a measure group containing these measures:
Distinct count of user_id
Count of switches (basically just the row count of the source data)
This measure group could then be related to the following dimensions:
Date, so you can see when the switches are taking place
User, so you can drill down on who is switching
Switch Type, which is a dimension built from the selecting the old_package_id and new_package_id from your source data. This gives you the ability to see the popularity of particular shifts.